Skip to content

[Python] Wait for AsyncWrapper work before teardown - #40507

Open
bvolpato wants to merge 4 commits into
apache:masterfrom
bvolpato:bvolpato/python-async-teardown
Open

bvolpato wants to merge 4 commits into
apache:masterfrom
bvolpato:bvolpato/python-async-teardown

Conversation

@bvolpato

@bvolpato bvolpato commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

AsyncWrapper.teardown() can close the wrapped DoFn's resources while background work still uses them. A bounded DirectRunner pipeline reports DONE, then a delayed write fails with ValueError: I/O operation on closed file.

This change tracks work owned by each wrapper and waits for it before tearing down the wrapped DoFn. Asyncio tasks stay tracked through cancellation cleanup, and the shared executor and event loop remain available to other wrappers.

The AsyncWrapper tests and DirectRunner reproductions passed locally in both thread-pool and asyncio modes. Teardown has no timeout, so hung processing or cleanup can delay shutdown. Pending-output delivery and timer behavior are unchanged.

Run the Python unit suite with:

./gradlew :sdks:python:test-suites:tox:py312:testPython312

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

See CONTRIBUTING.md for contribution guidelines.

@codecov

codecov Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.46%. Comparing base (76f6e6d) to head (269130a).
⚠️ Report is 303 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #40507      +/-   ##
============================================
+ Coverage     56.16%   56.46%   +0.29%     
  Complexity     2288     2288              
============================================
  Files          1124     1127       +3     
  Lines        178336   178889     +553     
  Branches       1489     1487       -2     
============================================
+ Hits         100170   101012     +842     
+ Misses        75645    75356     -289     
  Partials       2521     2521              
Flag Coverage Δ
python 80.03% <100.00%> (+0.47%) ⬆️

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.

@bvolpato
bvolpato marked this pull request as ready for review October 23, 2026 13:41

@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 a race condition in AsyncWrapper.teardown() where the wrapped DoFn's resources could be torn down while background thread-pool futures or asyncio tasks owned by that wrapper instance were still running or cleaning up after cancellation. The per-instance tracking of futures and asyncio tasks (while keeping the shared executor and event loop alive for other instances) and the accompanying unit and DirectRunner tests are well-structured.

🔍 General Feedback

  • Consider guarding teardown() against AsyncWrapper._event_loop being None (e.g., if _sync_fn.setup() fails before the event loop is started, or if reset_state() is called prior to teardown()) and initializing _pending_futures / _pending_async_tasks in __init__ as well as setup().

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

def teardown(self):
"""Forwards to the wrapped dofn's teardown method."""
"""Waits for this instance's work before tearing down the wrapped dofn."""
if self._use_asyncio:

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.

🟡 Medium: If teardown() is called when AsyncWrapper._event_loop is None (for example, if self._sync_fn.setup() raises an exception before the event loop thread is initialized in setup(), or if AsyncWrapper.reset_state() has already been called), asyncio.run_coroutine_threadsafe(self._wait_for_async_tasks(), AsyncWrapper._event_loop) will raise an AttributeError (and emit an unawaited coroutine warning for _wait_for_async_tasks()), preventing self._sync_fn.teardown() from running.

Additionally, initializing self._pending_futures = set() and self._pending_async_tasks = set() in __init__ as well as setup() (or using getattr) would avoid an AttributeError if teardown() or schedule_if_room() is called on an instance where setup() was not run.

Suggested change
if self._use_asyncio:
if self._use_asyncio and AsyncWrapper._event_loop is not None:

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @damccorm for label python.
Backup reviewer: tvalentyn (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).

@damccorm

Copy link
Copy Markdown
Contributor

@dustin12 would you mind taking a first look at this one?

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