Skip to content

[YAML] Add error_handling to ReadFromCsv and ReadFromJson - #41186

Open
codewarnab wants to merge 7 commits into
apache:masterfrom
codewarnab:yaml-file-read-error-handling
Open

codewarnab wants to merge 7 commits into
apache:masterfrom
codewarnab:yaml-file-read-error-handling

Conversation

@codewarnab

Copy link
Copy Markdown

Fixes #41081

What this does

Beam YAML ReadFromCsv and ReadFromJson now accept error_handling:

- type: ReadFromCsv
  config:
    path: gs://bucket/raw/*.csv
    error_handling:
      output: errors

Good records go to the main output. Bad records go to errors, and the pipeline keeps running.

Each error row uses the standard YAML error format (element, msg, stack). The element has:

  • path: the file that the record came from
  • record: the raw text of the bad record

A record is "bad" when:

  • CSV: it has the wrong number of fields, or a value does not match the column type.
  • JSON: the line is not valid JSON, is not a JSON object, or a value does not match the column type.
  • Both: the line is not valid UTF-8.

Without error_handling, nothing changes. The code calls apache_beam.io.ReadFromCsv / ReadFromJson exactly as before.

Why this approach

The current readers parse each file chunk with pandas. When one row is bad, pandas fails the whole chunk. We cannot tell which row was bad.

So, only when error_handling is set, this PR uses a separate read path in yaml_io.py:

  1. Read one sample from the first file (first 100 records) to get the column names and types. This is the same idea as the current reader.
  2. Read each file line by line, and group lines into records. A quoted CSV field with newlines stays in one record.
  3. Parse each record on its own with pandas, using the column types from step 1.
  4. If parsing fails, send the record to the error output.

I picked this option because:

  • It does not touch the shared pandas reader (apache_beam/dataframe/io.py). Other users of that reader are not affected.
  • It only runs when a user asks for error_handling.
  • The diff stays small and is easy to review.

Other option: change the pandas-based reader itself, so that it can report bad rows. That is a bigger change. If maintainers prefer it, I am happy to do that instead.

Known limits

  • Files are read one by one, not split into pieces. This is slower for very large files.
  • Column types come from the first 100 records of the first file. If a bad value is in those 100 records, the column type may become string, and that value is not reported as an error.
  • ReadFromJson with error_handling supports newline-delimited JSON only. This is already the YAML default.

Testing

New tests in yaml_io_test.py:

  • CSV: good rows, a quoted field with a newline, a wrong type, an extra field, and invalid UTF-8.
  • JSON: good lines, a broken line, and a line that is not an object.
  • CSV without error_handling still fails on a bad row, as before.

I also ran the existing yaml_io_test.py, yaml_transform_test.py and yaml_provider_unit_test.py. They all pass.


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.

@github-actions github-actions Bot added python yaml size/m M: 50-249 lines changed labels Nov 11, 2026
When error_handling is set, the files are read record by record, and
records that fail to parse go to the error output instead of failing
the pipeline. Without error_handling, nothing changes.

Fixes apache#41081
@codewarnab
codewarnab force-pushed the yaml-file-read-error-handling branch from 6286b5b to 8d34b58 Compare November 11, 2026 01:37

@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 adds error_handling dead-letter output support to ReadFromCsv and ReadFromJson in Beam YAML by introducing _ReadFilesWithErrors for record-by-record parsing. While the overall structure integrates well with Beam YAML's error handling conventions, there are several issues around Beam schema consistency (object vs pd.StringDtype()), JSON record validation (parse_record accepting JSON arrays or empty samples), CSV comment/quote handling, and missing Reshuffle for parallel file reading.

🔍 General Feedback

  • Schema Consistency (object vs pd.StringDtype()): Without error_handling, ReadViaPandas converts object columns to pd.StringDtype() so string columns map to Optional[str] in Beam's schema instead of Any. _ReadFilesWithErrors does not perform this conversion, which changes the output PCollection schema when error_handling is enabled.
  • Parallelism: Adding a beam.Reshuffle() between MatchFiles and ReadMatches is important so that reading multi-file globs distributes work across workers rather than running sequentially in a single fused bundle.

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

Comment thread sdks/python/apache_beam/yaml/yaml_io.py Resolved
Comment thread sdks/python/apache_beam/yaml/yaml_io.py Resolved
Comment thread sdks/python/apache_beam/yaml/yaml_io.py Resolved
Comment thread sdks/python/apache_beam/yaml/yaml_io.py Resolved
Comment thread sdks/python/apache_beam/yaml/yaml_io.py Resolved
- Use the string dtype for text columns, as ReadFromCsv does.
- ReadFromJson: send non-object lines and unknown fields to errors.
- ReadFromJson: fail clearly when the sample has no JSON objects.
- ReadFromCsv: skip comment lines before joining quoted lines, and
  count fields with pandas so inline comments work.
- ReadFromCsv: send records to errors when a file header differs.
- Add Reshuffle so that files are read in parallel.
- Clean up the test temp directory.
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @chamikaramj for label yaml.
Backup reviewer: derrickaw (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 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.52542% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.56%. Comparing base (d9eccaa) to head (654a413).
⚠️ Report is 180 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/yaml/yaml_io.py 91.52% 10 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41186      +/-   ##
============================================
+ Coverage     58.54%   58.56%   +0.01%     
  Complexity     2277     2277              
============================================
  Files          1132     1132              
  Lines        169697   169815     +118     
  Branches       1485     1485              
============================================
+ Hits          99354    99456     +102     
- Misses        67799    67815      +16     
  Partials       2544     2544              
Flag Coverage Δ
python 80.55% <91.52%> (+<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.

@codewarnab

Copy link
Copy Markdown
Author

Hi @chamikaramj @derrickaw, could either of you review this when you have time? I’ve addressed the automated review comments. I’d especially appreciate feedback on the separate read path used when error_handling is enabled. Thanks!

With ``error_handling``, each record is parsed on its own, and records
that fail to parse go to the error output instead of failing the pipeline.
Each error row has the source file path and the raw record text.
The column types come from the first 100 records of the first file.

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.

Why 100 ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I used 100 because Beam's existing reader (ReadViaPandas) also looks at the first 100 rows to work out the column types: apache_beam/dataframe/io.py#L288-L290. Using the same number means turning on error_handling gives the same types as leaving it off. I can make it a shared constant or a setting if you prefer.



# The number of records used to infer column types when error_handling is set.
_SAMPLE_SIZE = 100

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.

Ditto. Any reason to justify 100 as the sample size here ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Same reason as above.

Comment thread sdks/python/apache_beam/yaml/yaml_io.py Outdated
return df

def parse_file(lines, proxy):
dtypes = proxy.dtypes.drop(filename_column, errors='ignore').to_dict()

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.

CSV error path crashes when filename_column is unset.

Series.drop(None) always raises ValueError: Need to specify at least one of 'labels', 'index' or 'columns'. The error comes from inside the DoFn, so the pipeline fails on workers. Every CSV probe without filename_column failed this way.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You're right, sorry I missed that. The tests always set filename_column, so this case never ran. Fixed in 10ca961, and added a test that reads a CSV without filename_column.

df = parse()
if self._filename_column:
df[self._filename_column] = path
df = df.astype(proxy.dtypes)

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.

JSON path silently coerces bad values into "good" rows.

df.astype(proxy.dtypes) converts values instead of checking them. Sample types are count: int64, flag: bool.

Turning on a dead-letter queue should never make data less correct.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, I could reproduce this. For example, "false" and null in a boolean column both became True, and 3.7 in an integer column became 3. Fixed in 08481d3: each JSON value is now checked against its column type instead of converted, so these lines go to the error output. Added a test with one bad value of each kind.

Comment thread sdks/python/apache_beam/yaml/yaml_io.py Outdated
_SAMPLE_SIZE = 100


def _join_quoted_lines(lines, comment=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.

Quote joining is quadratic and misattributes records

record.count('"') rescans the whole growing record for every line. One unclosed quote (a truncated line, one of the issue's main examples) makes it absorb the rest of the file.

Also,
Good rows end up in the error output. pandas treats a quote in the middle of a field as a literal character, but the parity check doesn't.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, I could reproduce all of these. Fixed in 75fdd2d: records are now split with the csv module, which uses the same quote rules as pandas, so a quote in the middle of a field like 5"ft stays a normal value. It reads each line once, so it no longer slows down on long files. If a quote is never closed, only that line goes to the error output and reading continues from the next line. The type sample uses the same records, so an unclosed quote in the first 100 rows no longer fails the pipeline. Added a test that covers these cases.

match = beam_io.filesystems.FileSystems.match([self._path], limits=[1])[0]
if not match.metadata_list:
raise FileNotFoundError(f'Found no files that match {self._path!r}')
with beam_io.filesystems.FileSystems.open(

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.

Compressed input breaks with error_handling.

.csv.gz with error_handling fails at construction: 'CompressedFile' object has no attribute 'writable' (from io.TextIOWrapper).
Without error_handling, the same file reads. So this is a regression for CSV.
After that, for line in handle would fail too: TypeError: 'CompressedFile' object is not iterable

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, I could reproduce this for both .csv.gz and .json.gz. Fixed in af13592: the error path now passes the binary handle to pandas, the same as ReadFromCsv does, and reads lines with readline(), so compressed files work. Added tests for both.

This is just a progress update, the PR is not ready for another review yet. I'm still working on the JSON type coercion and the quote handling, including an unclosed quote in the first 100 rows, which currently fails the pipeline instead of going to the error output.

@chamikaramj

Copy link
Copy Markdown
Contributor

waiting on author

@codewarnab
codewarnab marked this pull request as draft November 23, 2026 18:20
@codewarnab
codewarnab marked this pull request as ready for review November 24, 2026 17:51
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.

[Feature Request]: [YAML] Support error_handling dead-letter output on ReadFromCsv and ReadFromJson

2 participants