Skip to content

[Python/Enrichment] Add FileEnrichmentHandler and on_miss/prefix/error_handling support (#41356) - #41423

Closed
shikhabhadoria wants to merge 4 commits into
apache:masterfrom
shikhabhadoria:feat-file-enrichment-handler-41356
Closed

shikhabhadoria wants to merge 4 commits into
apache:masterfrom
shikhabhadoria:feat-file-enrichment-handler-41356

Conversation

@shikhabhadoria

Copy link
Copy Markdown
Contributor

Summary

Addresses #41356.

This PR adds a file-backed lookup handler (FileEnrichmentHandler) and on_miss, prefix, and error_handling dead-letter routing semantics to Enrichment (apache_beam.transforms.enrichment and apache_beam.yaml.yaml_enrichment):

  1. FileEnrichmentHandler (apache_beam.transforms.enrichment_handlers.file):
    • Loads .parquet, .csv/.tsv, and .json/.jsonl reference tables via Beam FileSystems in worker __enter__, sharing the in-memory lookup dictionary across worker threads using apache_beam.utils.shared.Shared.
    • Supports join_key (and row_key), select_fields projection, and static output schema inference (get_output_schema()).
  2. on_miss & prefix Controls (apache_beam.transforms.enrichment.Enrichment):
    • Adds on_miss modes:
      • 'null' (default): left-join semantics, populating known enriched fields with None when 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 a KeyError on missing keys to fail the pipeline.
    • Adds prefix to cross_join and Enrichment to prefix enriched column names and avoid silent field collisions.
    • Infers output RowTypeConstraint when the source handler provides a static schema.
  3. Beam YAML error_handling Integration (apache_beam.yaml.yaml_enrichment & RequestResponseIO):
    • Registers 'File': FileEnrichmentHandler in yaml_enrichment.enrichment_transform.
    • Decorates enrichment_transform with @maybe_with_exception_handling_transform_fn and adds with_exception_handling support to RequestResponseIO and Enrichment so both RPC timeouts/failures and on_miss: dlq misses are routed to the standard Beam YAML error_handling dead-letter output.

Checklist

  • If this contribution is large, please file an Apache Individual Contributor License Agreement.
  • Replace these instructions with a description of your change and why you have made it.
  • Mention the appropriate issue in your description (for example: addresses #123 or fixes #456).
  • Update CHANGES.md with noteworthy changes.

@github-actions github-actions Bot added python io core yaml size/xl XL: >=1000 lines changed labels Nov 17, 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 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 or Any in Optional[...] should be guarded or checked carefully, especially when FileEnrichmentHandler.get_output_schema() falls back to (field, Any) on unresolvable paths at pipeline construction time.
  • JSON Format Handling: FileEnrichmentHandler._load_json currently only checks text.startswith('[') when self._format == 'json', which will fail on multi-line JSON objects or JSON arrays when file_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 bytes or str in memory before passing to csv.DictReader or pq.read_table works for reference tables, though pq.read_table can read directly from the file-like object returned by FileSystems.open without an intermediate f.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:

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.

🟡 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.

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.

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}

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.

🟠 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.

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.

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:

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.

🟡 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.

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.

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:

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.

🟡 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.

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.

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)

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.

🟢 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.

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.

Added "File" and FileEnrichmentHandler to the enrichment_transform docstring.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

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

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 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).

@derrickaw

Copy link
Copy Markdown
Collaborator

/gemini review

@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 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.py ensures FileEnrichmentHandler works even when optional GCP extras (google-cloud-bigtable, google-cloud-aiplatform) are not installed.
  • Output schema inference (infer_output_type) and _EnrichmentJoinFn cover all on_miss modes (null, drop, dlq, fail) and prefix combinations with thorough unit test coverage.

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

@codecov

codecov Bot commented Nov 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.89242% with 97 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.97%. Comparing base (bad3652) to head (8bf37f5).
⚠️ Report is 11 commits behind head on master.

Files with missing lines Patch % Lines
...apache_beam/transforms/enrichment_handlers/file.py 80.68% 73 Missing ⚠️
sdks/python/apache_beam/transforms/enrichment.py 87.50% 19 Missing ⚠️
sdks/python/apache_beam/yaml/yaml_enrichment.py 60.00% 4 Missing ⚠️
sdks/python/apache_beam/io/requestresponse.py 96.29% 1 Missing ⚠️
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              
Flag Coverage Δ
python 80.58% <82.89%> (-0.21%) ⬇️

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.

@derrickaw

Copy link
Copy Markdown
Collaborator

Hi @shikhabhadoria, can you break this PR up into 2 or 3 components to make reviewing easier? Thanks

@shikhabhadoria

Copy link
Copy Markdown
Contributor Author

Split this into three stacked PRs so each piece can be reviewed on its own. Please merge them in order:

  1. [Python] Add with_exception_handling to RequestResponseIO and Enrichment (#41356) #41451 — on_miss, prefix, and dead-letter plumbing on Enrichment / RequestResponseIO
  2. [Python] Add FileEnrichmentHandler for Parquet, CSV, and JSON (#41356) #41452 — FileEnrichmentHandler (Parquet, CSV/TSV, JSON/JSONL)
  3. [Python/YAML] Add File enrichment handler and error_handling (#41356) #41453 — Beam YAML File handler, on_miss, prefix, and error_handling

Each branch was tested on its own (enrichment, requestresponse, file, and YAML enrichment unit tests, plus ruff check). Closing this PR in favor of those.

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.

2 participants