Skip to content

[Interactive Beam] Fix caching deadlock, wait race conditions, and stale graph in notebooks#39161

Open
ian-Liaozy wants to merge 4 commits into
apache:masterfrom
ian-Liaozy:master
Open

[Interactive Beam] Fix caching deadlock, wait race conditions, and stale graph in notebooks#39161
ian-Liaozy wants to merge 4 commits into
apache:masterfrom
ian-Liaozy:master

Conversation

@ian-Liaozy

Copy link
Copy Markdown
Contributor

This PR resolves several critical caching issues in Interactive Beam when executing pipelines in notebook environments (like Colab), preventing deadlocks, duplicate execution of runner jobs, and stale dependency resolution.

Changes:

  1. Fix Background Thread Deadlock:
    Updated _wait_for_dependencies to skip checking the target PCollection itself when executing inside the background thread (indicated by the presence of async_result). This avoids a self-deadlock where the background thread blocked waiting for its own future to resolve.

  2. Fix Wait Race Condition:
    Previously, calling future.result() in _wait_for_dependencies was insufficient because the future resolves before the _on_done callback finishes executing to mark the PCollection as computed. This created a race condition where the main thread resumed, saw the PCollection was still "uncomputed", and started a duplicate execution job.
    We resolved this by introducing a threading.Event (_completed_event) in AsyncComputationResult that is set at the very end of _on_done. The main thread now blocks on comp.wait_for_completion(), guaranteeing that it only continues after the PCollection is fully marked as computed.

  3. Recalculate Uncomputed PCollections:
    Updated record() to recalculate the subset of remaining uncomputed PCollections after the dependency wait completes. If a PCollection finished computing during the wait, it skips the duplicate fragment execution.

  4. Fix Stale Pipeline Graph:
    Removed caching of the PipelineGraph in RecordingManager. Re-creating the graph dynamically ensures that any new transforms added by users in subsequent notebook cells are correctly detected and resolved as dependencies.

  5. Unit Tests Added:
    Added three new tests to recording_manager_test.py covering:

    • Deadlock avoidance and waiting behavior depending on async_result.
    • Dynamic recreation of the PipelineGraph when new transforms are appended.
    • Recalculation of uncomputed PCollections in record() after wait completion.

fixes #37220

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

…ph in Colab.

- Resolve self-deadlock in background thread: Updated `_wait_for_dependencies` to exclude target PCollections from the wait list when called from the background thread (i.e. when `async_result` is provided), allowing it to only wait on upstream dependencies.
- Fix duplicate execution race condition: Replaced waiting on `future.result()` with a `threading.Event` (`_completed_event`) set at the very end of `_on_done`. This ensures `collect()` only resumes after the background job has fully marked the PCollection as computed.
- Recalculate uncomputed PCollections: Added a check in `record()` to re-evaluate computed PCollections after waiting, preventing the launch of duplicate pipeline fragments for PCollections that completed during the wait.
- Fix stale pipeline graph: Removed caching of the `PipelineGraph` in `RecordingManager`. Re-creating the graph dynamically ensures that new transforms added in subsequent Colab cells are correctly detected and computed.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses critical stability issues in Interactive Beam when running within notebook environments. By refining how background threads handle dependencies and ensuring that the pipeline graph is dynamically refreshed, the changes prevent common race conditions and deadlocks that previously led to stale state or duplicate execution of pipeline fragments.

Highlights

  • Deadlock Prevention: Updated dependency checking to skip the target PCollection when executing in a background thread, preventing self-deadlocks.
  • Race Condition Resolution: Introduced a threading.Event to ensure the main thread waits until PCollection computation is fully finalized, preventing duplicate execution jobs.
  • Dynamic Graph Updates: Removed caching of the PipelineGraph to ensure that new transforms added in notebook cells are correctly detected and processed.
  • Improved Dependency Handling: Added logic to recalculate uncomputed PCollections after waiting for dependencies, skipping redundant work if a PCollection finishes during the wait.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request improves the reliability and correctness of asynchronous computations in the RecordingManager by introducing a threading.Event to wait for completion, ensuring cleanup in _on_done via a finally block, and dynamically recreating the pipeline graph to avoid stale caches. It also updates dependency waiting logic and recalculates uncomputed PCollections after waiting to prevent redundant runs. The reviewer feedback is highly valuable, pointing out a critical thread-safety issue where concurrent modification of _async_computations could raise a RuntimeError, and suggesting a lock-based solution. Additionally, the reviewer suggests a cleaner, more idiomatic way to compute the set difference of uncomputed PCollections.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +808 to +810
for dep in pcolls_to_check:
is_computing = self._env.is_pcollection_computing(dep)
if is_computing:

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.

high

Iterating over self._async_computations.values() (line 811) while another thread concurrently modifies the dictionary (e.g., in _on_done via pop()) will raise a RuntimeError: dictionary changed size during iteration.

To prevent this, we should protect accesses to self._async_computations using a lock.

Please define a lock in RecordingManager.__init__:

self._lock = threading.Lock()

And update _wait_for_dependencies to copy the values under the lock before iterating:

    with self._lock:
      async_computations_copy = list(self._async_computations.values())

    for dep in pcolls_to_check:
      is_computing = self._env.is_pcollection_computing(dep)
      if is_computing:
        for comp in async_computations_copy:
          if dep in comp._pcolls:
            computing_deps[dep] = comp

Comment on lines +178 to +179
self._env.unmark_pcollection_computing(self._pcolls)
self._recording_manager._async_computations.pop(self._display_id, None)

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.

high

To ensure thread safety and prevent RuntimeError when _wait_for_dependencies iterates over _async_computations, we should pop the computation from the dictionary under the same lock.

Suggested change
self._env.unmark_pcollection_computing(self._pcolls)
self._recording_manager._async_computations.pop(self._display_id, None)
self._env.unmark_pcollection_computing(self._pcolls)
with self._recording_manager._lock:
self._recording_manager._async_computations.pop(self._display_id, None)

Comment on lines +898 to +901
computed_pcolls = set(
pcoll for pcoll in pcolls
if pcoll in ie.current_env().computed_pcollections)
uncomputed_pcolls = set(pcolls).difference(computed_pcolls)

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

This set comprehension and subsequent difference can be simplified into a single, more efficient, and idiomatic statement using set.difference directly on ie.current_env().computed_pcollections.

      uncomputed_pcolls = set(pcolls).difference(
          ie.current_env().computed_pcollections)

@github-actions

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @claudevdm for label python.

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

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.

[Feature Request]: ib.collect support wait_for_inputs option

1 participant