Skip to content

[Python] Add native Expect transform for data quality validation - #41845

Open
sakshammalik260-cse wants to merge 2 commits into
apache:masterfrom
sakshammalik260-cse:feat/41223-expect-transform
Open

sakshammalik260-cse wants to merge 2 commits into
apache:masterfrom
sakshammalik260-cse:feat/41223-expect-transform

Conversation

@sakshammalik260-cse

@sakshammalik260-cse sakshammalik260-cse commented Dec 1, 2026 •

Copy link
Copy Markdown

Description

Part of #41223.

This PR introduces a native Expect PTransform 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

  • Added a native schema-aware Expect PTransform.
  • Implemented restricted SQL-style Boolean expression evaluation.
  • Added support for dlq, drop, and fail violation actions.
  • Added configurable tagged dead-letter outputs.
  • Added structured violation metadata.
  • Implemented per-rule pass and quarantine metrics using Beam's Metrics API.
  • Preserved input schemas, timestamps, and windows.
  • Added unit tests, regression tests, and documentation.
  • Updated CHANGES.md.

No new production dependencies have been introduced.

Python Example

from apache_beam.transforms.expect import Expect

outputs = records | Expect(
    rules=[
        {
            "name": "positive_amount",
            "expression": "amount > 0.0",
            "on_violation": "dlq",
        }
    ],
    dlq_output="InvalidRecords",
)

valid = outputs["good"]
invalid = outputs["InvalidRecords"]

Testing

Fresh local verification was performed after separating the Python SDK implementation from the YAML integration.

Check Result
Tests passed 2,047
Tests failed 0
Tests skipped 20
Passing subtests 38
DirectRunner Passed
Embedded FnApiRunner Passed
Threaded workers Passed
Subprocess workers Passed
Ruff Passed
YAPF Passed
Pyrefly 0 errors
Gradle validateChanges Passed
Apache RAT Passed
Dependency integrity Passed

Additional verification covered:

  • Fixed and sliding windows.
  • Nested nullable schemas.
  • Multiple simultaneous rule violations.
  • NULL and UNKNOWN handling.
  • Malformed records and evaluator errors.
  • Serialization and metric wire representation.
  • Expression resource limits.
  • Independent execution without YAML integration.

Review Feedback

Following the initial review:

  • Separated the Python SDK and YAML integration.
  • Investigated all nine Gemini review findings against the submitted implementation.
  • Identified several findings referencing functionality that is not present in this implementation.
  • Reproduced an external-provider main-output resolution issue, which will be addressed in the YAML follow-up.
  • Updated the documentation and changelog to reflect the Python-only scope.
  • Reran local regression and validation checks.

Design Considerations

I would appreciate feedback on the following:

  • Supported SQL-style predicate dialect.
  • Violation precedence and UNKNOWN handling.
  • DLQ schema and reserved output names.
  • Metric naming and diagnostic counters.
  • Aggregate resource limits.
  • Runtime evaluator-error handling.

Known Limitations

  • The expression evaluator supports a restricted SQL-style dialect rather than complete SQL semantics.
  • Aggregate rule and configuration limits remain open for discussion.
  • Metrics follow runner retry semantics.
  • Remote cloud runners have not yet been verified.
  • YAML integration is intentionally excluded from this PR.

Checklist

  • Referenced the corresponding issue.
  • Separated Python SDK and YAML integration.
  • Added unit and regression tests.
  • Updated documentation.
  • Updated CHANGES.md.
  • Passed local formatting and static analysis checks.
  • Passed Apache license checks.
  • ICLA status to be confirmed.

Feedback and suggestions are welcome.

Thank you for reviewing this contribution!

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)

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

{
"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.

@github-actions github-actions Bot added python core yaml size/xl XL: >=1000 lines changed labels Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026

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

Hi @sakshammalik260-cse, thanks for the PR. Please address the gemini review comments and split this PR into maybe python and yaml pieces. Thanks!

@sakshammalik260-cse

Copy link
Copy Markdown
Author

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)
@sakshammalik260-cse sakshammalik260-cse changed the title [Python/YAML] Add native Expect transform for data quality validation [Python] Add native Expect transform for data quality validation Dec 1, 2026
@sakshammalik260-cse

Copy link
Copy Markdown
Author

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!

@sakshammalik260-cse

Copy link
Copy Markdown
Author

/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 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 Expect transform and the expression compiler (_ExpressionCompiler protocol 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.

@github-actions github-actions Bot removed the yaml label 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