Skip to content

[Java] Pin UnboundedScheduledExecutorService worker contextClassLoader to creator - #41871

Draft
damccorm wants to merge 2 commits into
masterfrom
fix/unbounded-executor-pin-context-classloader-46790017727
Draft

damccorm wants to merge 2 commits into
masterfrom
fix/unbounded-executor-pin-context-classloader-46790017727

Conversation

@damccorm

@damccorm damccorm commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Note: this PR was auto-generated by tooling. Before moving it out of draft, the author has done a full review of the PR, specifically evaluating it on the following criteria:

  • The PR is an appropriate fix for the issue (e.g. we're not changing a test to avoid a bug)
  • The PR is a simple fix to the issue (e.g. we're not adding infra when we could just modify a test)
  • The PR is not covering for other problems (e.g. if we're bumping timeouts, it is not because we're covering for a performance problem)

Full details of the methodology of generation and review can be found here - https://docs.google.com/document/d/14lj7ECVov4T4EdwmIzNlWrRGE3lLDMOwX5xUMGzaLoc/edit?usp=sharing

If you have concerns with the PR or with the underlying methodology used to generate this, please comment below - they will be addressed by the author not the tooling :)

Summary

Pins the contextClassLoader of lazily created UnboundedScheduledExecutorService worker threads to the ClassLoader captured when UnboundedScheduledExecutorService is constructed, preventing embedded FnHarness worker threads from inheriting a stale, closed Flink SafetyNetWrapperClassLoader from gRPC's shared executor pool.

Failing Run

Root Cause

  1. In both tests, FnHarness.main() ran on CreateEnvironment-thread, whose contextClassLoader was the current Flink job's live SafetyNetWrapperClassLoader (confirmed by JvmInitializers.beforeProcessing succeeding via ServiceLoader on CreateEnvironment-thread immediately before entering the instruction loop).
  2. FnHarness.main() constructs new UnboundedScheduledExecutorService() (FnHarness.java:285), which uses a ThreadPoolExecutor with corePoolSize = 0 and MoreExecutors.platformThreadFactory() without pinning contextClassLoader.
  3. When BeamFnControlClient$InboundObserver.onNext() later dispatches InstructionRequests on gRPC's static JVM-wide grpc-default-executor-N threads (which can still hold a closed SafetyNetWrapperClassLoader inherited from an earlier Flink job in the same JVM/TaskManager), ThreadPoolExecutor lazily creates new FnHarness worker threads inheriting that closed SafetyNetWrapperClassLoader.
  4. SerializableUtils$ContextualObjectInputStream.resolveClass() then calls ReflectHelpers.findClassLoader() → Class.forName(...) on the closed SafetyNetWrapperClassLoader and throws IllegalStateException.

Changes

  • sdks/java/core/src/main/java/org/apache/beam/sdk/util/UnboundedScheduledExecutorService.java: Captures Thread.currentThread().getContextClassLoader() at construction time and sets it on every thread created by the wrapped ThreadFactory.
  • sdks/java/core/src/test/java/org/apache/beam/sdk/util/UnboundedScheduledExecutorServiceTest.java: Added testWorkerThreadsInheritCreatorContextClassLoader verifying that lazily created worker threads inherit the constructing thread's contextClassLoader even when submitted from a thread with a different contextClassLoader.

Verification

  • Verified formatting conventions match repository google-java-format style (local host has JRE 21 / JDK 27 without JDK 17/21 javac, so full Gradle compilation, Spotless, Checker Framework, :sdks:java:core:test, and beam_PreCommit_Java_Flink_Versions.yml are verified in GitHub Actions).

Verification

  • Triggered .github/workflows/beam_PreCommit_Java_Flink_Versions.yml workflow run on branch: 46795176165

@damccorm damccorm added the test-failure-cleanup Automated test health and flake cleanup PRs label Dec 2, 2026
@damccorm

damccorm commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

@github-actions github-actions Bot added java core size/s S: 10-49 lines changed labels Dec 2, 2026

@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 classloader leak/stale classloader issue in UnboundedScheduledExecutorService where lazily spawned worker threads inherited the contextClassLoader of the task-submitting thread (such as a shared gRPC executor thread holding a closed Flink SafetyNetWrapperClassLoader) instead of the thread that constructed the executor service. The fix cleanly captures the creator thread's contextClassLoader at construction time and applies it in the ThreadFactory, accompanied by a targeted unit test.

🔍 General Feedback

  • Capturing Thread.currentThread().getContextClassLoader() during UnboundedScheduledExecutorService construction and pinning it on newly created worker threads is a clean, minimal, and idiomatic fix.
  • The unit test properly verifies that tasks submitted from a thread with a distinct contextClassLoader execute on worker threads using the creator's contextClassLoader, while cleaning up thread state and the executor in finally blocks.

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

@damccorm

damccorm commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Fixed Checker Framework [dereference.of.nullable] error on baseThreadFactory.newThread(runnable) in incremental commit 42efdb302aa. Dispatched fresh PreCommit Java Flink Versions verification run.

/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 fixes a classloader leak/stale classloader issue in UnboundedScheduledExecutorService where lazily created worker threads previously inherited the contextClassLoader of the submitting thread (such as a shared gRPC executor thread holding a closed Flink SafetyNetWrapperClassLoader) instead of the thread that constructed the executor service. The fix cleanly captures the creator thread's contextClassLoader at construction time and applies it in the ThreadFactory, accompanied by a targeted unit test.

🔍 General Feedback

  • Capturing Thread.currentThread().getContextClassLoader() in the UnboundedScheduledExecutorService constructor and setting it on threads created by MoreExecutors.platformThreadFactory() is clean, minimal, and properly annotated for Checker Framework nullness checks.
  • Because the constructor immediately submits the long-running TaskLauncher task, the unit test's subsequent submit call from a separate thread deterministically exercises lazy worker thread creation under a different submitting contextClassLoader.

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

@damccorm damccorm added the ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review label Dec 2, 2026
@codecov

codecov Bot commented Dec 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.58%. Comparing base (5307bd5) to head (42efdb3).

Additional details and impacted files
@@            Coverage Diff            @@
##             master   #41871   +/-   ##
=========================================
  Coverage     59.58%   59.58%           
  Complexity     5182     5182           
=========================================
  Files          1471     1471           
  Lines        188317   188317           
  Branches       3882     3882           
=========================================
  Hits         112205   112205           
  Misses        72699    72699           
  Partials       3413     3413           

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core java ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review size/s S: 10-49 lines changed test-failure-cleanup Automated test health and flake cleanup PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant