Skip to content

Reset stale BaseProxy connections on reused MultiProcessShared ports and clean up ML test children - #41668

Draft
damccorm wants to merge 2 commits into
masterfrom
fix/ml-inference-cleanup-spawned-children
Draft

damccorm wants to merge 2 commits into
masterfrom
fix/ml-inference-cleanup-spawned-children

Conversation

@damccorm

@damccorm damccorm commented Nov 25, 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

  1. Evict stale per-thread BaseProxy._address_to_local connections in sdks/python/apache_beam/utils/multi_process_shared.py whenever MultiProcessShared connects to a newly created server (or a different server address_file identity) on a recycled (host, port), as well as on unsafe_hard_delete() and dead-server cleanup.
  2. Add an autouse=True pytest fixture (cleanup_spawned_children) in sdks/python/apache_beam/ml/conftest.py that snapshots multiprocessing.active_children() before each ML test and terminates/joins any newly spawned live child processes on teardown.
  3. Add a deterministic regression test (test_reused_server_address_resets_stale_proxy_connection) and filter multiprocessing.active_children() against pre-existing PIDs in MultiProcessSharedSpawnProcessTest (sdks/python/apache_beam/utils/multi_process_shared_test.py).

Production Impact

  • Affected workloads: Python SDK pipelines on Cloud Dataflow, Prism, and PortableRunner using MultiProcessShared(spawn_process=True) — including RunInference with share_model_across_processes() (enabled by default for large models since Spawn MultiProcessShared RunInference models in dedicated processes (#40673) #40816), ModelManager model eviction/reloading, automatic side-input model refresh, and timeout garbage collection (unsafe_hard_delete()).
  • How the bug manifests: Python's multiprocessing.managers.BaseProxy caches per-thread TCP connections in a process-global _address_to_local dict keyed solely by (host, port), and BaseProxy._decref only closes tls.connection on the thread that happens to finalize the last proxy (leaving stale dead sockets attached to other long-lived SDK worker threads indefinitely). When a spawned MultiProcessShared server process exits (e.g., via unsafe_hard_delete(), model eviction, or crash) and the OS later assigns that recycled ephemeral port to a new server, connect() / acquire() succeed over fresh sockets, but the first RPC call (e.g., model.predict(...) or get_valid_tag(...)) on a worker thread that previously talked to the old server sends on the stale socket and immediately fails the bundle with RuntimeError: EOFError inside multiprocessing/managers.py (conn.recv()).
  • How this fix resolves it: MultiProcessShared tracks the (tag, st_ino, st_mtime_ns, st_ctime_ns) of each connected address_file per (host, port) and evicts BaseProxy._address_to_local[addr] whenever a newly spawned or distinct server occupies that address (or when unsafe_hard_delete() / failed connect removes a dead server), forcing proxies for the new server to establish fresh per-thread connections.

Root Cause

PR #40816 (027f6191a92) enabled spawn_process=True for MultiProcessShared models in RunInference and added active_children() teardown only to RunInferenceBaseTest.tearDown(). This exposed two separate issues:

  1. Stale BaseProxy._address_to_local connections on recycled ephemeral ports: Terminating spawned server processes after each test (or via unsafe_hard_delete() in production) released their loopback ephemeral ports back to the OS (32768..46883 odd ports on Linux), while Prism's reused LoopbackWorker thread retained closed sockets in BaseProxy._address_to_local[(host, port)]. Once ~25–30 servers had been cycled on a worker, birthday-paradox port reuse caused healthy tests (test_run_inference_impl_simple_examples_multi_process_shared_multi_copy, test_run_inference_impl_with_keyed_examples_many_mhs_max_models_hint, test_run_inference_unpicklable_data_multi_process_shared, and test_run_inference_impl_with_maybe_keyed_examples_multi_process_shared) to hit a stale socket on model.predict() / get_valid_tag() and fail with silent EOFError in multiprocessing/managers.py.
  2. Leaked SpawnProcess children across non-RunInferenceBaseTest ML suites: TFRunInferenceTest, SkLearnRunInferenceTest, VLLMInferenceTest, and other ML tests never terminated their spawned MultiProcessShared child processes until worker exit, leaving 8 leaked SpawnProcess children that broke MultiProcessSharedSpawnProcessTest.test_unsafe_hard_delete_missing_tag_is_noop on Windows 3.13.

Recent Occurrences

5 occurrences on master in the last 24 hours:

  • 45525815916 (2026-11-25) — PreCommit Python ML tests with ML deps installed (3.12 test_run_inference_impl_simple_examples_multi_process_shared_multi_copy & 3.13 test_run_inference_impl_with_keyed_examples_many_mhs_max_models_hint EOFError in multiprocessing/managers.py:828)
  • 45535145094 (2026-11-25) — Python tests (Windows 3.13 MultiProcessSharedSpawnProcessTest.test_unsafe_hard_delete_missing_tag_is_noop found 8 leaked SpawnProcess children)
  • 45622781598 (2026-11-25) — PreCommit Python ML tests with ML deps installed (3.12 test_run_inference_impl_simple_examples_multi_process_shared_multi_copy EOFError in multiprocessing/managers.py:828)
  • 45641139739 (2026-11-25) — PreCommit Python Coverage (3.11 test_run_inference_unpicklable_data_multi_process_shared EOFError on get_valid_tag in multiprocessing/managers.py:822)
  • 45641139390 (2026-11-25) — PreCommit Python ML tests with ML deps installed (3.13 test_run_inference_impl_with_maybe_keyed_examples_multi_process_shared EOFError in multiprocessing/connection.py:404)

Verification

  • Verified formatting with yapf==0.43.0 --style setup.cfg and syntax with py_compile.
  • Reproduced the exact EOFError deterministically on a reused worker thread before the fix, and verified test_reused_server_address_resets_stale_proxy_connection passes with the fix.
  • Ran pytest -v apache_beam/utils/multi_process_shared_test.py apache_beam/ml/inference/vllm_inference_test.py locally (34/34 passed) and both previously failing RunInferenceBaseTest cases (test_run_inference_impl_simple_examples_multi_process_shared_multi_copy and test_run_inference_impl_with_keyed_examples_many_mhs_max_models_hint, 3/3 passed).
  • Triggered beam_PreCommit_Python_ML.yml workflow run on branch: 45645069959 (all jobs passed)

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

Copy link
Copy Markdown
Contributor Author

/gemini review

@github-actions github-actions Bot added python size/s S: 10-49 lines changed labels Nov 25, 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 cleanly resolves the leaked MultiProcessShared child processes across ML tests by adding an autouse=True pytest fixture in sdks/python/apache_beam/ml/conftest.py and scoping multiprocessing.active_children() checks in MultiProcessSharedSpawnProcessTest to newly spawned PIDs. The teardown logic properly escalates from terminate() to kill() with bounded join timeouts.

🔍 General Feedback

  • In sdks/python/apache_beam/utils/multi_process_shared_test.py, a few earlier tests in MultiProcessSharedSpawnProcessTest (test_process_exits_on_unsafe_hard_delete, test_process_exits_on_unsafe_hard_delete_with_manager, and test_zombie_reaping_on_acquire) also select the server process from multiprocessing.active_children() without filtering out pre-existing PIDs; applying the same before_pids pattern there (or in setUp) could further harden the suite if other tests outside apache_beam/ml ever leak child processes.

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

@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.45%. Comparing base (cd22ba1) to head (eaa1045).
⚠️ Report is 17 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/ml/conftest.py 75.00% 4 Missing ⚠️
...s/python/apache_beam/utils/multi_process_shared.py 95.83% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41668      +/-   ##
============================================
+ Coverage     58.85%   59.45%   +0.59%     
- Complexity     2315     5156    +2841     
============================================
  Files          1135     1471     +336     
  Lines        170507   187820   +17313     
  Branches       1499     3828    +2329     
============================================
+ Hits         100351   111666   +11315     
- Misses        67608    72745    +5137     
- Partials       2548     3409     +861     
Flag Coverage Δ
python 80.68% <87.50%> (-0.23%) ⬇️

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.

@damccorm damccorm changed the title Clean up spawned MultiProcessShared child processes after ML tests Reset stale BaseProxy connections on reused MultiProcessShared ports and clean up ML test children Nov 25, 2026
@damccorm

Copy link
Copy Markdown
Contributor Author

/gemini review

@github-actions github-actions Bot added size/m M: 50-249 lines changed and removed size/s S: 10-49 lines changed labels Nov 25, 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 effectively resolves two issues caused by MultiProcessShared(spawn_process=True): stale per-thread BaseProxy sockets on recycled ephemeral ports and leaked child processes across ML test suites. The BaseProxy._address_to_local cache eviction in multi_process_shared.py, the autouse=True cleanup fixture in sdks/python/apache_beam/ml/conftest.py, and the accompanying regression tests in multi_process_shared_test.py are all well-structured, thread-safe, and thoroughly tested.

🔍 General Feedback

  • The server identity tracking via (tag, st_ino, st_mtime_ns, st_ctime_ns) and synchronized eviction of BaseProxy._address_to_local cleanly handle port reuse across server creations, dead server recovery, and unsafe_hard_delete().
  • Filtering multiprocessing.active_children() against before_pids across all MultiProcessSharedSpawnProcessTest cases nicely isolates the test assertions from any external child processes.

💡 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 Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

python ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review size/m M: 50-249 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