Repository navigation
[YAML] Add error_handling to ReadFromCsv and ReadFromJson - #41186
codewarnab wants to merge 7 commits into
Conversation
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
6286b5b to
8d34b58
Compare
There was a problem hiding this comment.
📋 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 (
objectvspd.StringDtype()): Withouterror_handling,ReadViaPandasconvertsobjectcolumns topd.StringDtype()so string columns map toOptional[str]in Beam's schema instead ofAny._ReadFilesWithErrorsdoes not perform this conversion, which changes the output PCollection schema whenerror_handlingis enabled. - Parallelism: Adding a
beam.Reshuffle()betweenMatchFilesandReadMatchesis 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.
- 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.
|
Assigning reviewers: R: @chamikaramj for label yaml. Note: If you would like to opt out of this review, comment Available commands:
The PR bot will only process comments in the main thread (not review comments). |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
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 |
| 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. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Ditto. Any reason to justify 100 as the sample size here ?
| return df | ||
|
|
||
| def parse_file(lines, proxy): | ||
| dtypes = proxy.dtypes.drop(filename_column, errors='ignore').to_dict() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| _SAMPLE_SIZE = 100 | ||
|
|
||
|
|
||
| def _join_quoted_lines(lines, comment=None): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
|
waiting on author |
…r-handling # Conflicts: # CHANGES.md
Fixes #41081
What this does
Beam YAML
ReadFromCsvandReadFromJsonnow accepterror_handling: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). Theelementhas:path: the file that the record came fromrecord: the raw text of the bad recordA record is "bad" when:
Without
error_handling, nothing changes. The code callsapache_beam.io.ReadFromCsv/ReadFromJsonexactly 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_handlingis set, this PR uses a separate read path inyaml_io.py:I picked this option because:
apache_beam/dataframe/io.py). Other users of that reader are not affected.error_handling.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
ReadFromJsonwitherror_handlingsupports newline-delimited JSON only. This is already the YAML default.Testing
New tests in
yaml_io_test.py:error_handlingstill fails on a bad row, as before.I also ran the existing
yaml_io_test.py,yaml_transform_test.pyandyaml_provider_unit_test.py. They all pass.Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
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, commentfixes #<ISSUE NUMBER>instead.CHANGES.mdwith noteworthy changes.See the Contributor Guide for more tips on how to make review process smoother.