Repository navigation
[Python] Add native Expect transform for data quality validation - #41845
sakshammalik260-cse wants to merge 2 commits into
Conversation
Add schema-aware data-quality expectations with tagged dead-letter outputs, per-rule routing, metrics, YAML integration, and regression tests. Generated-by: OpenAI Codex and Google Antigravity (AI-assisted development)
There was a problem hiding this comment.
{
"summary": "## 📋 Review Summary\n\nThis PR introduces the Expect PTransform for data quality validation in both the Python SDK and Beam YAML, supporting inline condition predicates, JSON Schema validation, statistical aggregations (min, max, mean, count), and error_handling dead-letter routing. While the core transform and test suite are thorough, there are several high-impact issues: a fatal TypeError when Expect is used in Beam YAML with language: python (or generic), broken YAML schema/doc generation due to unparseable type annotations in ErrorHandlingConfig, and streaming window violations in statistical checks when using CombineGlobally on non-globally windowed PCollections.\n\n## 🔍 General Feedback\n- YAML Provider Registration & Architecture: Registering Expect in yaml_mapping.create_mapping_providers() causes normalize_source_sink_types to rewrite type: Expect into Expect-generic or Expect-python, which causes yaml_create_transform to be passed as the first positional argument by MetaInlineProvider—crashing _ExpectYaml.__init__. Moreover, Expect already handles language internally via callable_Config, so it belongs in YamlProviders.create_builtin_provider() (in yaml_provider.py) rather than language-dispatched mapping providers, eliminating the need for special-case hacks in yaml_transform.py.\n- Dead-letter / Error Handling Integration: Instead of duplicating exception-handling and threshold logic, consider whether Expect can align more closely with ParDo.with_exception_handling and _MaybePValueWithErrors in yaml_errors.py so that Scope didn't need a special _native_expect_main_outputs tracking dict.\n- Windowing Support in Aggregations: Statistical checks (count, min, max, mean) use CombineGlobally(...) with defaults, which raises a ValueError in Beam if the input PCollection has non-global windowing (e.g., fixed or sliding windows in streaming pipelines).",
"comments": [
{
"path": "sdks/python/apache_beam/yaml/yaml_mapping.py",
"line": 717,
"side": "RIGHT",
"severity": "🔴 Critical",
"body": "create_mapping_providers wraps both 'python' and 'generic' transform dicts in MetaInlineProvider(python_transforms). When a user specifies language: python (or omits language, which defaults to 'generic' via normalize_source_sink_types when Expect is in _KNOWN_TRANSFORMS), MetaInlineProvider.create_transform invokes self._transform_factories[type](yaml_create_transform, **args). Because _ExpectYaml.__init__ does not accept yaml_create_transform as its first positional argument, any YAML pipeline using Expect with language: python or without language (when normalized to Expect-generic) will fail with TypeError: _ExpectYaml.__init__() got multiple values for argument ... or bind yaml_create_transform to condition.\n\nSince _ExpectYaml handles the language parameter directly (for Python/Callable conditions) and does not have a SQL/Calcite implementation, Expect should be registered as a single built-in transform in YamlProviders.create_builtin_provider() in yaml_provider.py (using InlineProvider) rather than in yaml_mapping.py.",
"suggestion": null
},
{
"path": "sdks/python/apache_beam/yaml/yaml_transform.py",
"line": 484,
"side": "RIGHT",
"severity": "🟠 High",
"body": "Adding 'Expect' to _KNOWN_TRANSFORMS while only registering Expect in python_transforms (and not sql_transforms) causes two issues:\n1. If a user specifies language: sql or language: calcite, normalize_source_sink_types rewrites the type to Expect-sql / Expect-calcite, which does not exist in any provider.\n2. The special-case spec['type'] != 'Expect' on line 513 only skips normalization when language is omitted; if a user explicitly writes language: python or language: generic, it still rewrites the type to Expect-python / Expect-generic and hits MetaInlineProvider.\n\nIf Expect is registered in YamlProviders.create_builtin_provider() instead of yaml_mapping.py, both this entry and the special case on line 513 can be removed completely.",
"suggestion": null
},
{
"path": "sdks/python/apache_beam/yaml/yaml_transform.py",
"line": 238,
"side": "RIGHT",
"severity": "🟠 High",
"body": "Scope already has a generic mechanism for transforms that return a dictionary of {'good': ..., error_output: ...} when error_handling is configured (lines 285-296 in Scope.compute_outputs). Here, _native_expect_main_outputs only triggers when isinstance(ptransform, Expect), which only happens in the inline Python provider case (not if Expect is executed via ExternalPythonProvider when dependencies are specified). Furthermore, if _ExpectYaml.expand simply returns result['good'] when self._error_handling is None and {'good': result['good'], error_output: result[error_output]} when self._error_handling is set, Scope.compute_outputs (lines 285-296) will automatically resolve the main output and error output without needing _native_expect_main_outputs in yaml_transform.py at all.",
"suggestion": null
},
{
"path": "sdks/python/apache_beam/transforms/expect.py",
"line": 68,
"side": "RIGHT",
"severity": "🔴 Critical",
"body": "generate_yaml_docs.py parses ErrorHandlingConfig.__doc__ using docstring_parser and evaluates each parameter's type_name via PythonCallableWithSource.load_from_expression(param.type_name) (see generate_yaml_docs.py:137-146).\n\nBecause (float, optional) is not a valid Python expression (due to optional), running generate_yaml_docs.py (used in CI and documentation builds) will fail with a NameError: name 'optional' is not defined when generating docs for any transform with an error_handling parameter. Use (Optional[float]) instead.",
"suggestion": " threshold (Optional[float]): Maximum allowed failure ratio in [0.0, 1.0]."
},
{
"path": "sdks/python/apache_beam/transforms/expect.py",
"line": 343,
"side": "RIGHT",
"severity": "🟠 High",
"body": "beam.CombineGlobally(...) (with has_defaults=True, the default) raises a ValueError: Default values are not yet supported in CombineGlobally() if the output PCollection is not windowed by GlobalWindows whenever the input PCollection uses non-global windows (such as FixedWindows or SlidingWindows in streaming pipelines).\n\nFor min, max, and mean, you don't need a default value on empty windows (or for count, as_singleton_view() can be used, or without_defaults() when appropriate), or you should handle non-global windowing so Expect can be used after WindowInto.",
"suggestion": null
},
{
"path": "sdks/python/apache_beam/transforms/expect.py",
"line": 391,
"side": "RIGHT",
"severity": "🟠 High",
"body": "Similar to the statistical checks, CountTotal uses CombineGlobally(sum).as_singleton_view() directly on pcoll. If pcoll has non-global windowing and CountBad fires, or if error_handling is used on a windowed stream, consider aligning this with _ExceptionHandlingWrapper._post_process_result in apache_beam/transforms/core.py (which also divides bad / total safely and reports the window and ratio in the error message).",
"suggestion": null
},
{
"path": "sdks/python/apache_beam/transforms/expect.py",
"line": 225,
"side": "RIGHT",
"severity": "🟡 Medium",
"body": "jsonschema.validate(instance=instance, schema=self._schema) re-validates the schema specification and builds a validator on every single element. In a DoFn processing millions of records, this adds significant CPU overhead. Pre-compile the validator in setup() (e.g., self._validator = jsonschema.validators.validator_for(self._schema)(self._schema)) and call self._validator.validate(instance) in process().",
"suggestion": null
},
{
"path": "sdks/python/apache_beam/transforms/expect.py",
"line": 212,
"side": "RIGHT",
"severity": "🟡 Medium",
"body": "_row_to_dict only converts top-level Row or NamedTuple instances, leaving nested beam.Row objects inside fields or lists as Row instances rather than dicts. jsonschema requires JSON-compatible dicts for nested "type": "object" validation and will fail with ValidationError: BeamSchema_... is not of type 'object' on nested rows.\n\nConsider converting nested rows recursively (similar to to_dict in yaml_provider.py, though preserving None values if needed for nullable schema checks).",
"suggestion": null
},
{
"path": "sdks/python/apache_beam/transforms/expect.py",
"line": 284,
"side": "RIGHT",
"severity": "🟡 Medium",
"body": "value = _extract_field_value(element, self._field) is called outside the try block. If an element is a dict or Row that is missing self._field (raising KeyError or AttributeError), the exception will crash the pipeline instead of routing the failing element to the dead-letter output when error_handling is configured. Moving _extract_field_value inside the try block allows missing-field errors on malformed records to be captured by error_handling.",
"suggestion": null
}
]
}
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
|
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). |
|
Hi @sakshammalik260-cse, thanks for the PR. Please address the gemini review comments and split this PR into maybe python and yaml pieces. Thanks! |
Thanks for the feedback, @derrickaw! I'll go through the Gemini review comments individually, verify the reported issues against the current implementation, and split the contribution into separate Python SDK and YAML integration pieces. I'll start with the native Python transform and its tests, then prepare the YAML integration as a follow-up PR. Thanks for the guidance! |
Separate YAML integration into a follow-up contribution in response to reviewer feedback. Generated-by: OpenAI Codex (AI-assisted development)
|
Thanks for the feedback, @derrickaw! I've split the contribution as suggested. This PR now contains only the native Python SDK implementation and its tests. The YAML integration will follow separately. I've also investigated all nine Gemini review findings. Several reference functionality that isn't present in this implementation. However, I reproduced the external-provider main-output resolution issue and will address it in the YAML follow-up. The updated Python-only contribution passed 2,047 local tests with zero failures, along with static analysis, formatting, and license checks. Thanks again for the guidance! |
|
/gemini review |
There was a problem hiding this comment.
📋 Review Summary
This PR introduces the provisional Expect PTransform (apache_beam.transforms.expect.Expect) and its bounded SQL-style expression evaluator (_expect_expression.py) for schema-aware data quality validation in the Python SDK. The implementation is clean, well-structured, and thoroughly tested across expression parsing, three-valued logic, resource limits, routing policies (dlq, drop, fail), metrics, and local runners.
🔍 General Feedback
- The separation between the core Python
Expecttransform and the expression compiler (_ExpressionCompilerprotocol and_expect_expression.compile_predicate) is clean and modular. - Resource limits (expression length, token count, AST nesting, scalar size bounds, and evaluation step budgets) and runtime schema checks are well-designed and thoroughly covered by conformance tests.
- Routing precedence (
fail>dlq>drop), DLQ schema generation, and step-scoped Beam metrics behave consistently and are well-documented.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
Description
Part of #41223.
This PR introduces a native
ExpectPTransform for schema-aware data quality validation in the Python SDK.The goal is to simplify data quality validation by allowing users to define declarative rules and handle invalid records without writing custom DoFns or manual filtering logic.
Following reviewer feedback, I have separated the YAML integration from this PR. It will be submitted as a separate follow-up contribution.
Changes
dlq,drop, andfailviolation actions.No new production dependencies have been introduced.
Python Example
Testing
Fresh local verification was performed after separating the Python SDK implementation from the YAML integration.
Additional verification covered:
Review Feedback
Following the initial review:
Design Considerations
I would appreciate feedback on the following:
Known Limitations
Checklist
Feedback and suggestions are welcome.
Thank you for reviewing this contribution!