Skip to content

[Python] Add with_exception_handling to RequestResponseIO and Enrichment (#41356) - #41451

Open
shikhabhadoria wants to merge 6 commits into
apache:masterfrom
shikhabhadoria:feat-enrichment-on-miss-prefix-41356
Open

shikhabhadoria wants to merge 6 commits into
apache:masterfrom
shikhabhadoria:feat-enrichment-on-miss-prefix-41356

Conversation

@shikhabhadoria

@shikhabhadoria shikhabhadoria commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Add with_exception_handling to RequestResponseIO and Enrichment, forwarding to DoFn.with_exception_handling so RPC and join failures can be routed to a dead-letter output.

This PR is intentionally scoped to exception handling only. on_miss / prefix semantics are deferred to a follow-up branch (feat-enrichment-on-miss-prefix-followup-41356) per review feedback.

Related issue

Fixes part of #41356

Changes

  • RequestResponseIO.with_exception_handling(*args, **kwargs) and _Call.with_exception_handling(*args, **kwargs) forward to DoFn.with_exception_handling
  • When batching is enabled, expand failed (batch, error) records to per-element (request, error) for a consistent DLQ shape
  • Enrichment.with_exception_handling wires RRIO and join through the same API and flattens error outputs

Testing

  • enrichment_test.py: RPC timeout DLQ routing, join failure DLQ routing, cross_join

Give Enrichment explicit miss policy and column prefixing, and thread
dead-letter outputs through RequestResponseIO so misses and RPC failures
can be quarantined.
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

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.

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 damccorm 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.
…pache#41356)

Stop learning null enriched fields from prior hits. Without a static
handler schema, unmatched rows keep only their input fields so miss
output does not depend on processing order.
@shikhabhadoria

Copy link
Copy Markdown
Contributor Author

@JunaidAhamed-7777 Good catch. Without a static handler schema, _null_fields was being learned from the first hit on that DoFn instance, so a miss before any hit kept only the input fields while a miss after a hit got null filled enriched columns. That made miss output order dependent across workers.

I removed that learning path. For on_miss="null":

  • If the handler provides a static schema (get_output_schema() or a known column list), unmatched rows still get those enriched fields set to None.
  • If it does not, unmatched rows keep only their input fields, and that is consistent whether the miss is processed before or after a hit.

Added test_on_miss_null_schemaless_miss_first_is_stable covering miss first and hit first. pytest on enrichment_test.py and requestresponse_test.py is 18 passed.

@github-actions github-actions Bot added size/l L: 250-999 lines changed and removed size/m M: 50-249 lines changed labels Nov 20, 2026
@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.03922% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 59.49%. Comparing base (e24d1b9) to head (bde171a).
⚠️ Report is 63 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/io/requestresponse.py 96.55% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41451      +/-   ##
============================================
+ Coverage     58.89%   59.49%   +0.60%     
- Complexity     2315     5156    +2841     
============================================
  Files          1135     1470     +335     
  Lines        170578   187893   +17315     
  Branches       1499     3828    +2329     
============================================
+ Hits         100454   111782   +11328     
- Misses        67580    72709    +5129     
- Partials       2544     3402     +858     
Flag Coverage Δ
python 80.73% <98.03%> (-0.22%) ⬇️

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.

…ling

Address review feedback by keeping this change focused on
with_exception_handling. Forward *args/**kwargs to DoFn.with_exception_handling,
document that API, and keep FlattenBatchErrors for batched DLQ shape.
Move on_miss/prefix work to feat-enrichment-on-miss-prefix-followup-41356.
@shikhabhadoria shikhabhadoria changed the title [Python] Add on_miss and prefix semantics to Enrichment (#41356) [Python] Add with_exception_handling to RequestResponseIO and Enrichment (#41356) Nov 26, 2026
@github-actions github-actions Bot added the size/m M: 50-249 lines changed label Nov 26, 2026
@shikhabhadoria

Copy link
Copy Markdown
Contributor Author

@damccorm thanks for the review. Addressed all three comments:

  1. with_exception_handling(*args, **kwargs) now mirrors DoFn.with_exception_handling, with docs pointing there.
  2. Kept FlattenBatchErrors and documented why: batched failures arrive as (batch_list, error) and need per-element expansion for a consistent DLQ.
  3. Removed on_miss / prefix from this PR so it stays focused on exception handling. That work is on feat-enrichment-on-miss-prefix-followup-41356 for a follow-up.

Also merged latest master and resolved CHANGES.md.

@github-actions github-actions Bot added Next Action: Reviewers and removed size/l L: 250-999 lines changed Next Action: Author labels Nov 26, 2026
shikhabhadoria added a commit to shikhabhadoria/beam that referenced this pull request Nov 26, 2026
Refresh the branch onto latest master per review. Update skip/error
messages so on_miss/prefix point at the follow-up to apache#41451, while
error_handling continues to use with_exception_handling from that PR.
@github-actions github-actions Bot added size/l L: 250-999 lines changed Next Action: Reviewers and removed size/m M: 50-249 lines changed Next Action: Author labels Dec 1, 2026
Comment on lines +794 to +809
input_count_view = input_pcoll | 'CountTotal' >> (
_MaybeWindow() | beam.Map(lambda _: 1)
| beam.CombineGlobally(sum).as_singleton_view())
bad_count_pcoll = error_pcoll | 'CountBad' >> (
_MaybeWindow() | beam.Map(lambda _: 1)
| beam.CombineGlobally(sum).without_defaults())

def _check_threshold(bad, total, threshold_val, window=beam.DoFn.WindowParam):
if bad > total * threshold_val:
raise ValueError(
'The number of failing elements within the window %r '
'exceeded threshold: %s / %s = %s > %s' %
(window, bad, total, bad / total, threshold_val))

_ = bad_count_pcoll | 'CheckThreshold' >> beam.Map(
_check_threshold, input_count_view, threshold)

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.

Two notes on _check_exception_threshold:

  1. Batched callers + threshold_windowing mismatch / ZeroDivisionError: BatchElements emits batches at window.max_timestamp() (_GlobalWindowsBatchingDoFn uses GlobalWindow().max_timestamp(), _WindowAwareBatchingDoFn uses window.max_timestamp()). Because CountTotal re-windows the pre-batch requests/input_row using original event timestamps while CountBad re-windows the post-batch errors/all_errors at window.max_timestamp(), CountTotal and CountBad land in different threshold_windowing windows when batching is enabled. input_count_view then defaults to total = 0, which both falsely triggers bad > total * threshold_val and raises ZeroDivisionError on bad / total at line 806.
    • Could we raise a clear ValueError in RequestResponseIO.expand (when self._batching_kwargs) and Enrichment.expand (when self._source_handler.batch_elements_kwargs()) if threshold_windowing is not None and threshold is not None and threshold < 1.0 (advising users to window inputs before the transform instead), and also guard ratio = bad / total if total else float('inf') here?
  2. Nit (update-compat): Please give the two beam.Map(lambda _: 1) steps explicit static labels (e.g., 'ToOne' >> beam.Map(lambda _: 1)) so line numbers aren't baked into the transform names (see the comment at core.py:2425-2428).


def _build_do_outputs_tuple(
pipeline,
main_tag: 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.

Nit: main_tag: Optional[str] matches pvalue.DoOutputsTuple.__init__ since ParDo.with_exception_handling(main_tag=None) allows None.

Comment on lines +224 to +226
join_errors = (
join_result[dead_letter_tag]
| "NormalizeJoinErrors" >> beam.Map(lambda x: (x[0][0], x[1])))

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.

Nit: if a misbehaving handler returns None or (), _join_element fails to unpack and x[0][0] here would raise an unhandled TypeError/IndexError. Guarding with lambda x: (x[0][0], x[1]) if isinstance(x[0], tuple) and len(x[0]) == 2 else x handles that safely while still working for use_custom_types=True tuple requests (since valid fetched_data entries are always (request, response) 2-tuples).

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