Repository navigation
[Python/Enrichment] Add FileEnrichmentHandler and on_miss/prefix/error_handling support (#41356) - #41423
[Python/Enrichment] Add FileEnrichmentHandler and on_miss/prefix/error_handling support (#41356)#41423shikhabhadoria wants to merge 4 commits into
Conversation
…r_handling support (apache#41356)
There was a problem hiding this comment.
📋 Review Summary
This PR adds a file-backed enrichment handler (FileEnrichmentHandler) supporting Parquet, CSV/TSV, and JSON/JSONL formats, and introduces on_miss, prefix, and error_handling (DLQ) semantics to Python Enrichment, RequestResponseIO, and Beam YAML. The overall design is clean, uses shared.Shared effectively for worker-level lookup caching, and includes solid unit test coverage.
🔍 General Feedback
- Optional Type Narrowing: When inferring schema types for
on_miss='null'or CSV/JSON columns with nulls, wrapping an already-Optional[T]type orAnyinOptional[...]should be guarded or checked carefully, especially whenFileEnrichmentHandler.get_output_schema()falls back to(field, Any)on unresolvable paths at pipeline construction time. - JSON Format Handling:
FileEnrichmentHandler._load_jsoncurrently only checkstext.startswith('[')whenself._format == 'json', which will fail on multi-line JSON objects or JSON arrays whenfile_format='jsonl'isn't strictly single-line, and more importantly will attempt line-by-line JSONL parsing on pretty-printed JSON files or raise unhelpful errors on non-array JSON root objects. - Memory / Streaming during Parquet & CSV Loading: Reading the entire file into
bytesorstrin memory before passing tocsv.DictReaderorpq.read_tableworks for reference tables, thoughpq.read_tablecan read directly from the file-like object returned byFileSystems.openwithout an intermediatef.read()buffer copy.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
| responses = call_result[main_tag] | ||
| errors = call_result[dead_letter_tag] | ||
|
|
||
| if self._batching_kwargs: |
There was a problem hiding this comment.
🟡 Medium: When self._cache is enabled alongside with_exception_handling, cache misses or errors inside self._cache.get_read() and self._cache.get_write() are not protected by with_exception_handling, and more importantly cached_responses may have a mismatched coder/type hint or fail beam.Flatten() if responses is empty or typed differently by ParDo.with_exception_handling. Additionally, if self._cache is configured, responses written to cache in line 868 includes empty miss responses (e.g., (request, beam.Row())), which is existing behavior, but if an exception occurs in _Call, cached_responses still need to be flattened even when self._batching_kwargs is used. Consider extracting the post-call batch flattening and cache write/flatten logic so it isn't duplicated between the exception-handling and non-exception-handling branches.
There was a problem hiding this comment.
Deduplicated the post-call batch flattening and cache write/flatten logic between the exception-handling and non-exception-handling branches.
| yield self._join_fn(request, response) | ||
| return | ||
| left_dict = self._to_dict(request) | ||
| right_dict: dict[str, Any] = {f: None for f in self._null_fields} |
There was a problem hiding this comment.
🟠 High: When self._on_miss == 'null' and the handler does not provide a static output schema (e.g. BigQueryEnrichmentHandler, BigTableEnrichmentHandler, VertexAIFeatureStoreEnrichmentHandler, or FileEnrichmentHandler without select_fields when the file isn't accessible at graph construction time), self._null_fields is []. In that case, a lookup miss yields beam.Row(**left_dict) containing only the input columns, whereas a lookup hit yields beam.Row containing the input columns plus the enriched columns. Having rows with different sets of fields in the same output PCollection breaks Beam schema consistency and downstream transforms (such as Beam YAML SQL/Filter/Map or schema coders) that expect a uniform Row schema across all elements.
There was a problem hiding this comment.
Updated Enrichment._get_handler_schema to also inspect known column list attributes (select_fields, column_names, feature_ids, feature_names, output_fields), added _EnrichmentJoinFn.setup() to resolve worker-side get_output_schema(), and guarded _make_optional_type against wrapping Any or already-optional types.
| raw_rows: list[dict[str, Optional[str]]] = [] | ||
| fieldnames: list[str] = [] | ||
| for file_path in file_paths: | ||
| with FileSystems.open(file_path, 'rb') as f: |
There was a problem hiding this comment.
🟡 Medium: If multiple CSV files are matched by a glob pattern (e.g., part-*.csv) and have columns in different orders or a first file that is empty (header-only or 0 bytes), fieldnames is only captured from the first non-empty reader.fieldnames, and _determine_target_columns isn't validated against subsequent files. Also, decoding with 'utf-8' when CSV files contain a UTF-8 BOM (\ufeff) will cause the first column name in fieldnames to include '\ufeff', causing _determine_target_columns to fail with a confusing KeyError when join_key is the first column. Using 'utf-8-sig' as the default or stripping BOM when self._encoding.lower() in ('utf-8', 'utf8') prevents this common CSV pitfall.
There was a problem hiding this comment.
Updated _load_csv to decode UTF-8 files with utf-8-sig (stripping UTF-8 BOMs) and validate target columns against each non-empty CSV file.
| """Returns the static `(field_name, field_type)` schema of enriched fields.""" | ||
| if self._cached_schema is not None: | ||
| return list(self._cached_schema) | ||
| try: |
There was a problem hiding this comment.
🟡 Medium: get_output_schema() is called at pipeline construction time inside Enrichment.infer_output_type() and Enrichment.expand(). Loading the entire reference dataset into memory on the runner/submission machine during graph construction can be very slow or fail with OOM/auth errors if the reference file is large or resides on a remote filesystem only accessible to workers. For Parquet, you can inspect only the footer metadata via pq.read_schema(...) (and for CSV, only the header/sample if needed, or defer full table loading to __enter__), rather than materializing the full _LookupTable during pipeline construction.
There was a problem hiding this comment.
Added lightweight _peek_schema() in get_output_schema() that inspects Parquet footer metadata via pq.read_schema(f) and samples only the first 100 rows for CSV/JSONL instead of materializing the full lookup table at pipeline construction time.
| @@ -80,6 +89,11 @@ def enrichment_transform( | |||
| - [VertexAIFeatureStoreEnrichmentHandler](https://beam.apache.org/releases/pydoc/current/apache_beam.transforms.enrichment_handlers.vertex_ai_feature_store.html#apache_beam.transforms.enrichment_handlers.vertex_ai_feature_store.VertexAIFeatureStoreEnrichmentHandler) | |||
There was a problem hiding this comment.
🟢 Low: Please also list 'File' (FileEnrichmentHandler) in the enrichment_handler docstring and handler_config documentation above so that Beam YAML documentation generation includes the new File handler option.
There was a problem hiding this comment.
Added "File" and FileEnrichmentHandler to the enrichment_transform docstring.
|
Assigning reviewers: R: @derrickaw for label yaml. This pull request likely touches a core component ("core" label). Please review with scrutiny. 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). |
|
/gemini review |
There was a problem hiding this comment.
📋 Review Summary
This PR cleanly implements FileEnrichmentHandler (supporting Parquet, CSV/TSV, and JSON/JSONL reference tables shared across worker threads via apache_beam.utils.shared.Shared) along with on_miss, prefix, and error_handling dead-letter routing in Python Enrichment, RequestResponseIO, and Beam YAML. All feedback from the previous review round—including lightweight schema peeking at pipeline construction time, UTF-8 BOM handling in CSVs, and deduplicated post-call batch/cache handling in RequestResponseIO—has been properly addressed.
🔍 General Feedback
- The separation of optional GCP handler imports in
yaml_enrichment.pyensuresFileEnrichmentHandlerworks even when optional GCP extras (google-cloud-bigtable,google-cloud-aiplatform) are not installed. - Output schema inference (
infer_output_type) and_EnrichmentJoinFncover allon_missmodes (null,drop,dlq,fail) andprefixcombinations with thorough unit test coverage.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #41423 +/- ##
============================================
- Coverage 58.00% 57.97% -0.03%
Complexity 2733 2733
============================================
Files 1206 1207 +1
Lines 172522 173076 +554
Branches 2260 2260
============================================
+ Hits 100069 100342 +273
- Misses 69761 70042 +281
Partials 2692 2692
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 @shikhabhadoria, can you break this PR up into 2 or 3 components to make reviewing easier? Thanks |
|
Split this into three stacked PRs so each piece can be reviewed on its own. Please merge them in order:
Each branch was tested on its own ( |
Summary
Addresses #41356.
This PR adds a file-backed lookup handler (
FileEnrichmentHandler) andon_miss,prefix, anderror_handlingdead-letter routing semantics toEnrichment(apache_beam.transforms.enrichmentandapache_beam.yaml.yaml_enrichment):FileEnrichmentHandler(apache_beam.transforms.enrichment_handlers.file):.parquet,.csv/.tsv, and.json/.jsonlreference tables via BeamFileSystemsin worker__enter__, sharing the in-memory lookup dictionary across worker threads usingapache_beam.utils.shared.Shared.join_key(androw_key),select_fieldsprojection, and static output schema inference (get_output_schema()).on_miss&prefixControls (apache_beam.transforms.enrichment.Enrichment):on_missmodes:'null'(default): left-join semantics, populating known enriched fields withNonewhen a key is not found.'drop': inner-join semantics, dropping unmatched elements.'dlq': routes unmatched elements to the configured dead-letter output when exception handling is enabled.'fail': raises aKeyErroron missing keys to fail the pipeline.prefixtocross_joinandEnrichmentto prefix enriched column names and avoid silent field collisions.RowTypeConstraintwhen the source handler provides a static schema.error_handlingIntegration (apache_beam.yaml.yaml_enrichment&RequestResponseIO):'File': FileEnrichmentHandlerinyaml_enrichment.enrichment_transform.enrichment_transformwith@maybe_with_exception_handling_transform_fnand addswith_exception_handlingsupport toRequestResponseIOandEnrichmentso both RPC timeouts/failures andon_miss: dlqmisses are routed to the standard Beam YAMLerror_handlingdead-letter output.Checklist
addresses #123orfixes #456).CHANGES.mdwith noteworthy changes.