Skip to content

[Python] Add FileEnrichmentHandler for Parquet, CSV, and JSON (#41356) - #41452

Open
shikhabhadoria wants to merge 2 commits into
apache:masterfrom
shikhabhadoria:feat-file-enrichment-handler-io-41356
Open

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

Conversation

@shikhabhadoria

@shikhabhadoria shikhabhadoria commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Addresses #41356. Part 2 of 3. This branch is based on current master and contains only FileEnrichmentHandler. It does not repeat #41451.

Summary

Test plan

  • pytest apache_beam/transforms/enrichment_handlers/file_test.py — 8 passed
  • ruff check on the new handler and tests
  • Python precommit

Checklist

  • If this contribution is large, please file an Apache Individual Contributor License Agreement.
  • Mention the appropriate issue in the description (addresses #41356).
  • Update CHANGES.md with noteworthy changes.

@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 introduces FileEnrichmentHandler for Parquet, CSV/TSV, and JSON/JSONL reference tables using Beam's FileSystems and Shared handle, stacked on top of the on_miss and prefix enhancements in Enrichment. The implementation and test coverage are well-structured, though there are a few issues around null join-key matching, Parquet nullability in _peek_schema, and exception routing on on_miss='null' joins.

🔍 General Feedback

  • Ensure None lookup keys in input elements are always treated as misses rather than matching rows with missing/null keys in the reference file.
  • Keep Parquet schema inference in _peek_schema() consistent with nullable column values so non-'null' on_miss modes ('drop', 'fail', 'dlq') do not produce non-nullable RowTypeConstraint fields for nullable Parquet columns.

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


def get(self, key: Any) -> Optional[dict[str, Any]]:
if key is None:
return self.records.get(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.

🟠 High: _load_parquet, _load_csv, and _load_json insert records[None] = projected whenever a reference row has a null or empty join_key. Returning self.records.get(None) when the input row's lookup key is None causes null foreign keys in the input PCollection to falsely match those null-keyed reference rows instead of being treated as lookup misses. A None lookup key should always be a miss (and reference rows with key is None should not be indexed).

Suggested change
return self.records.get(None)
return None

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.

Fixed in d5e1279: _LookupTable.get(None) now returns None, and _load_parquet, _load_csv, and _load_json skip indexing rows where key is None.

with FileSystems.open(first_path, 'rb') as f:
arrow_schema = pq.read_schema(f)
target_cols = self._determine_target_columns(list(arrow_schema.names))
return [(c, _arrow_type_to_python_type(arrow_schema.field(c).type))

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: _peek_schema() ignores field nullability on the Arrow schema (arrow_schema.field(c).nullable) and always returns non-Optional types for Parquet columns. Because get_output_schema() caches _peek_schema() during pipeline construction, using Enrichment(handler, on_miss='drop') (or 'fail'/'dlq') on a Parquet reference file with nullable columns (such as 'opt_val': [1.0, None] in test_schema_inference_json_jsonl_and_arrow_types) sets a non-nullable RowTypeConstraint on the output PCollection, which fails when encoding None values at runtime. Check arrow_schema.field(c).nullable (or Parquet footer column chunk null_count statistics) and wrap in Optional[...] when nullable.

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.

Fixed in d5e1279: _peek_schema() now inspects the Parquet footer via pq.ParquetFile (using row-group column chunk null_count statistics, with fallback to field.nullable when statistics are unavailable) and wraps nullable columns in Optional[...].

right_dict: dict[str, Any] = {f: None for f in self._null_fields}
if self._prefix:
right_dict = {f"{self._prefix}{k}": v for k, v in right_dict.items()}
yield self._join_fn(left_dict, right_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.

🟡 Medium: In _EnrichmentJoinFn.process, the on_miss == 'null' branch invokes self._join_fn(...) outside the try ... except Exception as exn: block below (lines 179-200). If a custom join_fn raises an exception when handling a miss with on_miss='null' and with_exception_handling(...) is enabled, the exception will fail the pipeline instead of being routed to self._dead_letter_tag.

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.

The enrichment.py changes were split out into #41451 when this PR was rebased onto master, so this PR only touches FileEnrichmentHandler.

…#41356)

Load Parquet, CSV/TSV, and JSON/JSONL reference tables through Beam
FileSystems and share the in-memory lookup across worker threads.
@shikhabhadoria

Copy link
Copy Markdown
Contributor Author

Rebased this onto current master so the diff is only FileEnrichmentHandler. The earlier version also contained the #41451 commits, which is why GitHub was counting those lines again. This PR can merge on its own.

@github-actions github-actions Bot added size/l L: 250-999 lines changed and removed io size/xl XL: >=1000 lines changed labels Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @tvalentyn for label python.
Backup reviewer: damccorm (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).

@github-actions
github-actions Bot requested a review from tvalentyn November 18, 2026 17:18
shikhabhadoria added a commit to shikhabhadoria/beam that referenced this pull request Nov 19, 2026
…apache#41356)

Drop the unused json import flagged in review. Import FileEnrichmentHandler
separately so a missing module does not disable Enrichment, and skip the
file-handler tests until apache#41451 and apache#41452 are available.
@github-actions

Copy link
Copy Markdown
Contributor

Reminder, please take a look at this pr: @tvalentyn

@github-actions

Copy link
Copy Markdown
Contributor

Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment assign to next reviewer:

R: @damccorm for label python.
Backup reviewer: claudevdm (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.

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)

@damccorm

Copy link
Copy Markdown
Contributor

/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 adds FileEnrichmentHandler to support file-backed enrichment lookups against Parquet, CSV/TSV, and JSON/JSONL reference tables via Beam FileSystems, sharing the in-memory lookup table across worker threads with apache_beam.utils.shared.Shared. While the overall design and test coverage are solid, there are several bugs around null-key handling, Python bool/int dictionary key collisions, Parquet nullability in _peek_schema(), and schema inference over multiple files with heterogeneous columns.

🔍 General Feedback

  • Dictionary key equivalence (bool vs int): In Python, True == 1 and False == 0 with identical hashes, so storing raw keys directly in dict[Any, ...] causes collisions if a table mixes boolean and integer keys or lookups.
  • Null handling: Both reference table loading and get() index/match None keys, and multi-file JSON/CSV loaders omit None entries when a column is missing from earlier files, skewing nullability inference.

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


def get(self, key: Any) -> Optional[dict[str, Any]]:
if key is None:
return self.records.get(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.

🟠 High: _load_parquet, _load_csv, and _load_json insert records[None] = projected whenever a reference row has a null or empty join_key. Returning self.records.get(None) when key is None causes input rows with null lookup keys to falsely match null-keyed reference rows instead of being treated as lookup misses. get(None) should always return None (and reference rows with key is None should not be indexed in records).

Suggested change
return self.records.get(None)
return None

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.

Fixed in d5e1279: _LookupTable.get(None) now returns None, and rows with key is None are not indexed.

if key is None:
return self.records.get(None)
if key in self.records:
return self.records[key]

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: In Python, bool is a subclass of int (True == 1 and False == 0 with identical hashes). Because self.records is a standard dict, a lookup with key = True (or False) will match a reference record keyed by 1 (or 0), and vice versa. Consider keying self.records by (type(key), key) (or checking type compatibility) so boolean keys do not collide with integer keys 0 and 1.

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.

Fixed in d5e1279: records is now keyed by (type(key), key) and boolean keys are excluded from str_records, preventing bool/int collisions between True/False and 1/0.

types_seen = {type(v) for v in non_null}
if types_seen == {bool}:
base_type: Any = bool
elif types_seen == {int}:

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: Because bool is a subclass of int in Python, issubclass(bool, int) is True, though type(True) is bool. However, on line 167, types_seen <= {int, float} is only true for int and float, whereas if a JSON column has [True, 1], types_seen is {bool, int} which falls through to Any, and if a column has list values (like 'tags': ['a', 'b'] in test_schema_inference_json_jsonl_and_arrow_types), _infer_python_column_type returns Any instead of list (unlike _arrow_type_to_python_type which returns list[...]). If list or dict values are present, consider inferring list / dict when homogeneous.

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.

Fixed in d5e1279: _infer_python_column_type now infers list[elem_type] and dict[key_type, val_type] for homogeneous list and dict columns.

reader = csv.DictReader(io.StringIO(text), delimiter=self._delimiter)
if reader.fieldnames:
file_cols = list(reader.fieldnames)
self._determine_target_columns(file_cols)

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: In _load_csv, self._determine_target_columns(file_cols) is called inside the per-file loop before fieldnames is accumulated, and then called again on line 351. If file_paths matches multiple CSV files where a file has only headers (or empty files are skipped) or columns differ across files, calling _determine_target_columns on line 351 with an empty fieldnames list when all matched CSV files are empty raises a misleading KeyError: "join_key '...' not found in reference file columns: []".

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.

Fixed in d5e1279: removed the per-file _determine_target_columns call inside the loop, raised a clear ValueError when all matched CSV files are empty, and marked columns absent from a subset of files as Optional[...].

with FileSystems.open(first_path, 'rb') as f:
arrow_schema = pq.read_schema(f)
target_cols = self._determine_target_columns(list(arrow_schema.names))
return [(c, _arrow_type_to_python_type(arrow_schema.field(c).type))

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: _peek_schema() ignores field nullability on the Arrow schema (arrow_schema.field(c).nullable) and always returns non-Optional types for Parquet columns, whereas _load_parquet() wraps nullable columns in Optional[py_type]. Because get_output_schema() caches _peek_schema() before __enter__() runs, downstream consumers (such as schema-aware transforms or #41451's RowTypeConstraint) will receive a non-nullable type for nullable Parquet columns and fail at runtime when None values are present. Check arrow_schema.field(c).nullable and wrap py_type in Optional[py_type] when true.

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.

Fixed in d5e1279: _peek_schema() now wraps nullable Parquet columns in Optional[py_type].

if line.strip()
]
sample_rows = self._parse_json_text('\n'.join(lines), first_path)
else:

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._format == 'json', _peek_schema() reads the entire file (text_stream.read()) into memory and parses all JSON records just to infer the schema, even if the file is actually JSONL with a .json extension or a large JSON array. In addition, if sample_rows is empty (e.g., an empty file), _determine_target_columns(all_columns) raises KeyError, which get_output_schema() catches and silently caches [] in self._cached_schema if it didn't raise, or fails to cache.

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.

Fixed in d5e1279: added _sample_json_stream using json.JSONDecoder().raw_decode in chunks so _peek_schema() samples up to 100 records without reading the entire JSON file into memory, and avoided caching [] when no records are present.

state['_table'] = None
return state

def get_cache_key(self, request: beam.Row) -> str:

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: get_cache_key directly accesses request._asdict()[self._row_key] without checking if self._row_key is present, and formats the key with "%s: %s". Two distinct types with the same string representation (e.g. id=1 (int) and id='1' (str), or id=None and id='None') will produce the exact same cache key 'id: 1' or 'id: None'. When Enrichment.with_redis_cache(...) is used, this can cause cache collisions or Coder errors if input row types vary.

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.

Fixed in d5e1279: get_cache_key now validates that self._row_key is in the input row (raising KeyError if missing) and formats the value with !r so values with identical str() representations (such as 1 vs '1' or None vs 'None') produce distinct cache keys.

@github-actions github-actions Bot added size/xl XL: >=1000 lines changed and removed size/l L: 250-999 lines changed labels Dec 1, 2026
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