Skip to content

Do not run Python in the forked child when launching Spark's gateway - #113870

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-pyspark-gateway-fork-deadlock
Aug 9, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-pyspark-gateway-fork-deadlock

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

Related: #113636
Related: #110479
Related: #113697

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

test_spark_session_recovery timed out after 900 s on three unrelated PRs. The deepest frame is subprocess.py:1944, where the parent reads the forked child's CLOEXEC error pipe. The kernel closes it only once the child execs or dies, so blocking there means the child never reached exec: the job log has no spark-submit and no JAVA_GATEWAY_EXITED.

launch_gateway passes preexec_fn (java_gateway.py:96-97) to ignore SIGINT in the JVM. Both of CPython's exec-only launch paths require it to be None, so a plain fork() is used and Python runs in the child, which _posixsubprocess.c:1001 warns is "NOT SAFE if your application uses threads": a lock a sibling thread held at fork time is held in the child forever, so it never execs and the parent waits on a pipe nobody will close.

This change gives the launch start_new_session instead. The protection is preserved and stronger, since SIGINT goes to the foreground process group and the child no longer belongs to it, and no Python runs in the child, so CPython takes the vfork path. Only the Popen name launch_gateway resolves is rebound, once at import, so concurrent launches cannot strip each other's protection.

This test is the only one that relaunches the gateway inside a live pytest-xdist worker, which had 13 threads at the failure. Launching once at session start only makes the deadlock rarer, so all eight Spark suites now share this launch path.

The regression test carries its own pytest.mark.timeout, because the deadlock is inside the Popen constructor: the 900 s global bound was otherwise the only one, so a regression would stall a worker rather than report.

Validated both directions: unpatched, the test fails in 120.12 s at os.read(errpipe_read), the frame CI reported; with the fix it passes in 0.18 s. A mutant dropping preexec_fn without setting start_new_session fails the session-identity assertion.

groeneai and others added 3 commits August 7, 2026 17:04
test_spark_session_recovery timed out after 900 s on three unrelated pull
requests, with the deepest frame at subprocess.py:1944:

    java_gateway.py:97   proc = Popen(command, **popen_kwargs)
    subprocess.py:1039   __init__
    subprocess.py:1944   part = os.read(errpipe_read, 50000)

That line is the parent's "wait for exec to fail or succeed" loop, reading the
forked child's CLOEXEC error pipe, which the kernel closes only once the child
execs or dies. Blocking there means the child never reached exec, so no JVM was
ever started: the job log contains no spark-submit invocation and no
JAVA_GATEWAY_EXITED.

pyspark's launch_gateway passes preexec_fn (java_gateway.py:96-97) to ignore
SIGINT in the JVM. That argument rules out both of CPython's exec-only launch
paths, since posix_spawn requires preexec_fn to be None (subprocess.py:1863) and
so does vfork (_posixsubprocess.c:1227). A plain fork() is used instead and
_posixsubprocess.c:800-801 calls back into Python inside the child, under its own
comment "This is where the user has asked us to deadlock their program";
_posixsubprocess.c:1001 states the rule: "preexec_fn is NOT SAFE if your
application uses threads. It may trigger infrequent, difficult to debug
deadlocks." A lock a sibling thread held at fork time is held in the child
forever, so it never execs and the parent waits for a pipe nobody will close.

Translate that argument into start_new_session for the duration of the launch.
The protection pyspark wants is preserved and is stronger: SIGINT is delivered
to the foreground process group, and the child now has its own session and
group rather than merely ignoring the signal while sharing the parent's group.
No Python runs in the forked child, so CPython takes the vfork path, where the
parent is suspended until exec and this deadlock cannot occur. The replacement
is scoped to the launch so nothing else changes how it spawns processes.

This test is the only one that kills the gateway JVM and makes launch_gateway
run again inside a live pytest-xdist worker; every other Spark suite launches
the gateway once at session start. The failing worker had 13 live threads at
timeout, which is the threads-plus-fork-plus-Python condition above.

The new test reproduces the launch call rather than mocking it, so it hangs
instead of failing when the fix is reverted, and it also pins the scope: outside
the launch, preexec_fn reaches Popen untouched.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tity

Review found the first attempt patched a process-wide default and restored it
around each launch. Overlapping launches then strip each other's protection and
leave the wrapper installed for good, which is reachable: the concurrent Iceberg
read test drives one ResilientSparkSession from 15 threads, and any of them can
enter _restart. Measured against that version: the second context lost its
protection while still inside, and subprocess.Popen never returned to the
original.

Rebind pyspark.java_gateway.Popen once at import instead. launch_gateway resolves
Popen through its own module global, so that name alone is enough, and nothing
else in the process spawns differently. With no mutation and no restore there is
no window to race over; the rebind is idempotent, so importing the helper more
than once cannot double-wrap it.

The regression test also went through the helper directly, so it kept passing if
the launch stopped using it, and its exit-code oracle passed if the shim merely
dropped preexec_fn and lost Spark's signal isolation. It now launches through the
same name launch_gateway uses and has the child report whether it leads its own
session, so both mutants fail: reverting the rebind hangs at the CI frame, and
dropping preexec_fn without start_new_session fails the identity assertion.

Co-Authored-By: Claude Fable 5 <[email protected]>
The shim is installed as an import side effect of helpers.spark_tools, so it
reached only the suites that import that helper. test_paimon_spark_smoke and
test_storage_delta_shuffles build their sessions straight from
pyspark.sql.SparkSession, and both launch after cluster.start(), when the
worker already has live threads. Launching once does not make preexec_fn safe;
it only makes the deadlock rarer. They now import the helper too, so all eight
Spark suites share one launch path.

The regression test could only fail slowly. Its deadlock is inside the Popen
constructor, so proc.communicate(timeout=60) is never reached and the global
900 s timeout was the sole bound, i.e. a regression would stall a worker for
fifteen minutes rather than report. A pytest.mark.timeout keeps the failure
local; measured with the shim disarmed, the test now fails in 120.12 s at
os.read(errpipe_read), the frame CI reported, instead of hanging.

Verified: importing the helper arms the launcher and leaves subprocess.Popen
untouched, while a module that does not import it is unaffected. Both patched
suites arm it through their own imports, and the regression test passes in
0.18 s with the shim in place.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @zlareb1, could you review this? pyspark's gateway launch passes preexec_fn, which rules out CPython's exec-only launch paths, so a plain fork runs Python in the child and it can block forever on a lock a sibling thread held at fork time, timing out the test at 900 s; this replaces it with start_new_session and routes test_paimon_spark_smoke through the same launch.

@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [04647fd]

Summary: ✅


AI Review

Summary

This PR makes Spark gateway launch fork-safe in the integration harness by replacing PySpark's preexec_fn-based launch behavior with start_new_session, adds a focused regression test for the deadlock, and routes the two remaining direct Spark entrypoints through helpers.spark_tools. I found no actionable issues in the current diff. The change matches the pinned Spark launch contract used by the runner image, the regression test covers both the deadlock path and the session-isolation requirement, and the PR CI is green.

Missing context / blind spots
  • ⚠️ I could not execute the Spark regression locally because this shell does not have pyspark installed, so the verdict relies on code inspection and the green PR CI rather than a local rerun.
Final Verdict

✅ No actionable findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 7, 2026
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 04647fd

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks Not PR-caused. The build_profile_hook.py build-time-trace telemetry INSERT into the CI logs cluster is rejected with Code: 241 ... would use 42.13 GiB ... maximum: 29.80 GiB, OvercommitTracker decision, i.e. a memory-pressure spike on that shared cluster. This PR only changes four pyspark integration-test files and touches nothing in the CI telemetry path. Non-gating: the Build (arm_release) check-run itself is success, so the row is visible only in the results database. a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

All 175 check-runs completed with zero failing check-runs (36 success, 139 skipped);
Config Workflow and Finish Workflow are both success. The one failure above is a
sub-result inside an otherwise-green build job, so it does not appear in the checks API.

Why merged #113409 is deliberately not linked here. That PR ("Retry the build-profile
telemetry INSERT through the CI logs cluster memory-pressure spikes", merged
2026-08-06T00:05:00Z) is present in this build, so per the ledger rules it must not be listed
as the owner of a failure that happened with it applied. Presence was established per build
rather than from the merge date, two independent ways:

  • gh api compare/de947727b2ba...04647fd5e62d reports status=ahead, behind_by=0.
  • The retry count in the failure text is the discriminator: the pre-fix code calls
    do_query(..., retries=1) and emits at most one WARNING: LogCluster query failed
    line, while the merged fix passes retries=8. This row carries 8 such lines, so it
    provably ran post-fix code and exhausted every retry. The 5*(retry+1) backoff is at most
    ~140 s, which does not outlast the cluster memory spike.

Breadth over the last 7 days for this signature: 3061 rows across 847 distinct pull requests,
1256 of them on master, so it is environmental rather than specific to any branch.

Session id: cron:our-pr-ci-monitor:20260808-013000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 9, 2026
Merged via the queue into ClickHouse:master with commit de2f4d2 Aug 9, 2026
180 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants