Repository navigation
[Python] Add FileEnrichmentHandler for Parquet, CSV, and JSON (#41356) - #41452
shikhabhadoria wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
📋 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
Nonelookup 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_missmodes ('drop','fail','dlq') do not produce non-nullableRowTypeConstraintfields 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) |
There was a problem hiding this comment.
🟠 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).
| return self.records.get(None) | |
| return None |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
🟠 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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
🟡 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.
There was a problem hiding this comment.
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.
2bba387 to
1400fbd
Compare
|
Rebased this onto current master so the diff is only |
|
Assigning reviewers: R: @tvalentyn for label python. 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). |
…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.
|
Reminder, please take a look at this pr: @tvalentyn |
|
Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment R: @damccorm for label python. This pull request likely touches a core component ("core" label). Please review with scrutiny. Available commands:
|
|
/gemini review |
There was a problem hiding this comment.
📋 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 (
boolvsint): In Python,True == 1andFalse == 0with identical hashes, so storing raw keys directly indict[Any, ...]causes collisions if a table mixes boolean and integer keys or lookups. - Null handling: Both reference table loading and
get()index/matchNonekeys, and multi-file JSON/CSV loaders omitNoneentries 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) |
There was a problem hiding this comment.
🟠 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).
| return self.records.get(None) | |
| return None |
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
🟡 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.
There was a problem hiding this comment.
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}: |
There was a problem hiding this comment.
🟡 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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
🟡 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: []".
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
🟠 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.
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
🟡 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.
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
🟠 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.
There was a problem hiding this comment.
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.
…ma inference, and cache keys
Addresses #41356. Part 2 of 3. This branch is based on current master and contains only
FileEnrichmentHandler. It does not repeat #41451.Summary
FileEnrichmentHandlerfor.parquet,.csv/.tsv, and.json/.jsonlreference tables loaded through BeamFileSystems.__enter__and shares it across threads withapache_beam.utils.shared.Shared.join_key,row_key,select_fields, andget_output_schema()(Parquet footer or a CSV/JSON sample at construction time; full load on the worker).on_miss/prefixare [Python] Add with_exception_handling to RequestResponseIO and Enrichment (#41356) #41451. Beam YAML registration is [Python/YAML] Add File enrichment handler and error_handling (#41356) #41453, which should merge after both.Test plan
pytest apache_beam/transforms/enrichment_handlers/file_test.py— 8 passedruff checkon the new handler and testsChecklist
addresses #41356).CHANGES.mdwith noteworthy changes.