Skip to content

[Python] Preserve per-element event-time timestamps in batched RequestResponseIO / Enrichment (#41348) - #41433

Open
shikhabhadoria wants to merge 7 commits into
apache:masterfrom
shikhabhadoria:fix-batched-rrio-timestamps-41348
Open

shikhabhadoria wants to merge 7 commits into
apache:masterfrom
shikhabhadoria:fix-batched-rrio-timestamps-41348

Conversation

@shikhabhadoria

Copy link
Copy Markdown
Contributor

Summary

Fixes #41348.

When RequestResponseIO / Enrichment runs with batching enabled (self._batching_kwargs non-empty, e.g. BigQueryEnrichmentHandler or CloudSQLEnrichmentHandler):

  1. inputs | BatchElements(**self._batching_kwargs) emits each batch at window.max_timestamp() (END_OF_GLOBAL_WINDOW = Timestamp(9223371950454.774999) in GlobalWindows).
  2. FlattenBatch previously yielded un-timestamped elements from the batch, causing every enriched record to inherit END_OF_GLOBAL_WINDOW and breaking downstream WindowInto(FixedWindows(...)) and timestamp-sensitive sinks.

Changes

  • Added _AttachWindowMetadataDoFn and _WindowedRequest prior to BatchElements in RequestResponseIO.expand to capture each element's (timestamp, windows, pane_info) (while adapting element_size_fn, length_fn, and key_fn in batch_elements_kwargs to unwrap _WindowedRequest).
  • Updated _CallDoFn.process to unwrap raw requests before invoking self._repeater.repeat(self._caller, ...), re-associate each returned response with its corresponding request's windowing metadata (supporting both out-of-order (request, response) tuples and positional responses), and emit the batch at min(timestamps).
  • Updated FlattenBatch.process to emit windowed_value.WindowedValue(element.request, element.timestamp, element.windows, element.pane_info), preserving exact per-element event-time timestamps and windows.
  • Added unit tests in sdks/python/apache_beam/io/requestresponse_test.py and updated CHANGES.md.

Checklist

  • If this contribution is large, please file an Apache Individual Contributor License Agreement.
  • Replace these instructions with a description of your change and why you have made it.
  • Mention the appropriate issue in your description (for example: addresses #123 or fixes #456).
  • 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 fixes #41348 by preserving per-element event-time timestamps, windows, and pane metadata across BatchElements in RequestResponseIO and Enrichment. The approach cleanly wraps elements in _WindowedRequest prior to batching, unwraps them before invoking the Caller, re-associates responses (supporting both out-of-order (request, response) tuples and positional responses), and restores each element's WindowedValue in FlattenBatch.

🔍 General Feedback

  • Adapting element_size_fn, length_fn, and key_fn in _adapt_batching_kwargs ensures custom batch sizing predicates continue to receive the unwrapped request object.
  • The two-pass request matching in _reattach_window_metadata (identity fast-path followed by equality fallback and positional fallback) properly handles handlers that reorder responses or reconstruct beam.Row instances.
  • Unit tests thoroughly cover out-of-order batch responses, downstream FixedWindows aggregation, pre-windowed inputs, and metadata reattachment fallbacks.

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

@github-actions github-actions Bot added python io size/m M: 50-249 lines changed labels Nov 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @tvalentyn for label python.
Backup reviewer: shunping (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

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

@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 58.68%. Comparing base (66d6189) to head (6ad6911).
⚠️ Report is 73 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41433      +/-   ##
============================================
- Coverage     58.78%   58.68%   -0.10%     
  Complexity     2296     2296              
============================================
  Files          1135     1135              
  Lines        170282   170341      +59     
  Branches       1490     1490              
============================================
- Hits         100096    99964     -132     
- Misses        67642    67833     +191     
  Partials       2544     2544              
Flag Coverage Δ
python 80.64% <100.00%> (-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.

@tvalentyn

Copy link
Copy Markdown
Contributor

thanks, are you a user of RR IO?

@shikhabhadoria

Copy link
Copy Markdown
Contributor Author

Hi @tvalentyn, we encountered this through Enrichment (which uses RequestResponseIO under the hood). When using batched enrichment handlers (such as BigQueryEnrichmentHandler, where min_batch_size=1, max_batch_size=10000 is enabled by default, or custom batched EnrichmentSourceHandlers) on event-time streams in GlobalWindows prior to WindowInto(FixedWindows(...)), BatchElements + FlattenBatch was resetting every enriched element's timestamp to END_OF_GLOBAL_WINDOW.

@tvalentyn

Copy link
Copy Markdown
Contributor

/gemini review

@tvalentyn

Copy link
Copy Markdown
Contributor

i see. thanks, i can take a closer look in 2 weeks or so. if you would like a faster response, you can comment " assign to next reviewer "

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @shunping for label python.
Backup reviewer: damccorm (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

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 shunping November 18, 2026 16:19
@shikhabhadoria

Copy link
Copy Markdown
Contributor Author

Thanks @tvalentyn! Since the bot has already reassigned the review to @shunping, @shunping could you please take a look when you get a chance?

@shunping shunping left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution!

While I understand the logic of this PR, I have a design question.

Since BatchElements emits every batch at the end of its window by design, losing per-element event-time timestamps affects any caller of BatchElements (such as RequestResponseIO, RunInference, etc.).

I'm wondering whether we should handle this downstream in RequestResponseIO or push it upstream as an option/feature in BatchElements (e.g., returning WindowedValues or tracking element metadata) so other transforms can benefit as well.

Thoughts? @damccorm @tvalentyn

@damccorm

Copy link
Copy Markdown
Contributor

I'm wondering whether we should handle this downstream in RequestResponseIO or push it upstream as an option/feature in BatchElements (e.g., returning WindowedValues or tracking element metadata) so other transforms can benefit as well.

I think it would be nice, but in practice I'm having a hard time imagining an experience that makes sense for everyone. For example, take RunInference - it takes the outputs of the BatchElements call and feeds them directly into a model as a sequence - wrapping the elements in windowed objects wouldn't work here. Most downstream consumers probably don't actually care as well.

The place where it does make sense is where you're doing some batching -> an operation -> unbatching, which is not actually that generic IMO (and there is a workaround available as shown in this PR). Disclaimer, I haven't reviewed the PR so don't consider this an approval, but the approach generally is reasonable at least.

;tldr - I'm probably -1 on trying to make this generic.

@shunping

Copy link
Copy Markdown
Collaborator

I'm wondering whether we should handle this downstream in RequestResponseIO or push it upstream as an option/feature in BatchElements (e.g., returning WindowedValues or tracking element metadata) so other transforms can benefit as well.

I think it would be nice, but in practice I'm having a hard time imagining an experience that makes sense for everyone. For example, take RunInference - it takes the outputs of the BatchElements call and feeds them directly into a model as a sequence - wrapping the elements in windowed objects wouldn't work here. Most downstream consumers probably don't actually care as well.

The place where it does make sense is where you're doing some batching -> an operation -> unbatching, which is not actually that generic IMO (and there is a workaround available as shown in this PR). Disclaimer, I haven't reviewed the PR so don't consider this an approval, but the approach generally is reasonable at least.

;tldr - I'm probably -1 on trying to make this generic.

Makes sense—thanks for the input, @damccorm! I'm onboard with keeping this scoped to RequestResponseIO.

if idx < len(windowed_requests) else windowed_requests[-1])
wrapped.append(
_WindowedRequest(
resp_item,

@shunping shunping Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: It feels a bit confusing for _reattach_window_metadata to return a list[_WindowedRequest] (and for FlattenBatch to yield element.request) when the wrapped item at that point is actually the response.

Could we either rename _WindowedRequest / .request to something stage-neutral like _WindowedElement / .value, use a plain (value, timestamp, window, pane_info) tuple, or use apache_beam.utils.windowed_value.WindowedValue (keeping in mind that yielding a top-level WindowedValue from a DoFn is automatically unwrapped by Beam, so it can't be used directly as the pre-batch element wrapper)?

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.

Good catch. Renamed to _WindowedElement with a stage-neutral .value payload (request before the call, response afterward). FlattenBatch now yields element.value.

by_id[id(w.request)].append(w)
remaining: list[_WindowedRequest] = list(windowed_requests)

wrapped: list[_WindowedRequest] = []

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's worth adding a brief docstring or inline comments here to document the matching heuristics.

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.

Added a docstring on _reattach_window_metadata documenting the matching order: identity on (request, response) tuples, then equality for reconstructed values, then positional fallback, plus the scalar/beam.Row wrapping case.

Address review feedback: use stage-neutral _WindowedElement.value
instead of _WindowedRequest.request, and document identity/equality/
positional matching in _reattach_window_metadata.
@shikhabhadoria

shikhabhadoria commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@shunping thanks for the review. Addressed both comments in 84aa794:

  1. Renamed _WindowedRequest / .request to _WindowedElement / .value so the wrapper is stage-neutral across request and response.
  2. Documented the identity, equality, then positional matching heuristics on _reattach_window_metadata.

Also merged latest master and resolved the CHANGES.md conflict (kept both the #41348 note and the newer bugfix entries).

Agree with keeping this scoped to RequestResponseIO / Enrichment rather than generalizing BatchElements, per @damccorm.

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.

[Bug]: [Python] Batched Enrichment / RequestResponseIO resets per-element event-time timestamps to END_OF_GLOBAL_WINDOW

4 participants