Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-35303][PYTHON] Enable pinned thread mode by default #32429

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ private[spark] class Py4JServer(sparkConf: SparkConf) extends Logging {
// Java system properties and such
private val localhost = InetAddress.getLoopbackAddress()
private[spark] val server = if (sys.env.getOrElse(
"PYSPARK_PIN_THREAD", "false").toLowerCase(Locale.ROOT) == "true") {
"PYSPARK_PIN_THREAD", "true").toLowerCase(Locale.ROOT) == "true") {
new py4j.ClientServer.ClientServerBuilder()
.authToken(secret)
.javaPort(0)
Expand Down
6 changes: 1 addition & 5 deletions docs/job-scheduling.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,6 @@ in each corresponding JVM thread. Due to this limitation, it is unable to set a
via `sc.setJobGroup` in a separate PVM thread, which also disallows to cancel the job via `sc.cancelJobGroup`
later.

In order to synchronize PVM threads with JVM threads, you should set `PYSPARK_PIN_THREAD` environment variable
to `true`. This pinned thread mode allows one PVM thread has one corresponding JVM thread. With this mode,
`pyspark.InheritableThread` is recommended to use together for a PVM thread to inherit the inheritable attributes
such as local properties in a JVM thread.

Note that `PYSPARK_PIN_THREAD` is currently experimental and not recommended for use in production.
such as local properties in a JVM thread, and to avoid resource leak.

6 changes: 6 additions & 0 deletions python/docs/source/migration_guide/pyspark_3.1_to_3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,9 @@ Upgrading from PySpark 3.1 to 3.2
* In Spark 3.2, the PySpark methods from sql, ml, spark_on_pandas modules raise the ``TypeError`` instead of ``ValueError`` when are applied to an param of inappropriate type.

* In Spark 3.2, the traceback from Python UDFs, pandas UDFs and pandas function APIs are simplified by default without the traceback from the internal Python workers. In Spark 3.1 or earlier, the traceback from Python workers was printed out. To restore the behavior before Spark 3.2, you can set ``spark.sql.execution.pyspark.udf.simplifiedTraceback.enabled`` to ``false``.

* In Spark 3.2, pinned thread mode is enabled by default to map each Python thread to the corresponding JVM thread. Previously,
one JVM thread could be reused for multiple Python threads, which resulted in one JVM thread local being shared to multiple Python threads.
Also, note that now ``pyspark.InheritableThread`` or ``pyspark.inheritable_thread_target`` is recommended to use together for a Python thread
to properly inherit the inheritable attributes such as local properties in a JVM thread, and to avoid a potential resource leak issue.
To restore the behavior before Spark 3.2, you can set ``PYSPARK_PIN_THREAD`` environment variable to ``false``.
5 changes: 4 additions & 1 deletion python/docs/source/reference/pyspark.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Public Classes
BarrierTaskContext
BarrierTaskInfo
InheritableThread

util.VersionUtils

Spark Context APIs
------------------
Expand Down Expand Up @@ -239,6 +239,7 @@ Management
.. autosummary::
:toctree: api/

inheritable_thread_target
SparkConf.contains
SparkConf.get
SparkConf.getAll
Expand Down Expand Up @@ -279,3 +280,5 @@ Management
BarrierTaskContext.resources
BarrierTaskContext.stageId
BarrierTaskContext.taskAttemptId
util.VersionUtils.majorMinorVersion

4 changes: 2 additions & 2 deletions python/pyspark/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
from pyspark.rdd import RDD, RDDBarrier
from pyspark.files import SparkFiles
from pyspark.status import StatusTracker, SparkJobInfo, SparkStageInfo
from pyspark.util import InheritableThread
from pyspark.util import InheritableThread, inheritable_thread_target
from pyspark.storagelevel import StorageLevel
from pyspark.accumulators import Accumulator, AccumulatorParam
from pyspark.broadcast import Broadcast
Expand Down Expand Up @@ -125,5 +125,5 @@ def wrapper(self, *args, **kwargs):
"Accumulator", "AccumulatorParam", "MarshalSerializer", "PickleSerializer",
"StatusTracker", "SparkJobInfo", "SparkStageInfo", "Profiler", "BasicProfiler", "TaskContext",
"RDDBarrier", "BarrierTaskContext", "BarrierTaskInfo", "InheritableThread",
"__version__",
"inheritable_thread_target", "__version__",
]
5 changes: 4 additions & 1 deletion python/pyspark/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ from pyspark.taskcontext import ( # noqa: F401
BarrierTaskInfo as BarrierTaskInfo,
TaskContext as TaskContext,
)
from pyspark.util import InheritableThread as InheritableThread # noqa: F401
from pyspark.util import (
InheritableThread as InheritableThread, # noqa: F401
inheritable_thread_target as inheritable_thread_target, # noqa: F401
)
from pyspark.version import __version__ as __version__

# Compatibility imports
Expand Down
27 changes: 6 additions & 21 deletions python/pyspark/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -1104,13 +1104,8 @@ def setJobGroup(self, groupId, description, interruptOnCancel=False):
ensure that the tasks are actually stopped in a timely manner, but is off by default due
to HDFS-1208, where HDFS may respond to Thread.interrupt() by marking nodes as dead.

Currently, setting a group ID (set to local properties) with multiple threads
does not properly work. Internally threads on PVM and JVM are not synced, and JVM
thread can be reused for multiple threads on PVM, which fails to isolate local
properties for each thread on PVM.

To avoid this, enable the pinned thread mode by setting ``PYSPARK_PIN_THREAD``
environment variable to ``true`` and uses :class:`pyspark.InheritableThread`.
If you run jobs in parallel, use :class:`pyspark.InheritableThread` for thread
local inheritance, and preventing resource leak.

Examples
--------
Expand Down Expand Up @@ -1148,13 +1143,8 @@ def setLocalProperty(self, key, value):

Notes
-----
Currently, setting a local property with multiple threads does not properly work.
Internally threads on PVM and JVM are not synced, and JVM thread
can be reused for multiple threads on PVM, which fails to isolate local properties
for each thread on PVM.

To avoid this, enable the pinned thread mode by setting ``PYSPARK_PIN_THREAD``
environment variable to ``true`` and uses :class:`pyspark.InheritableThread`.
If you run jobs in parallel, use :class:`pyspark.InheritableThread` for thread
local inheritance, and preventing resource leak.
"""
self._jsc.setLocalProperty(key, value)

Expand All @@ -1171,13 +1161,8 @@ def setJobDescription(self, value):

Notes
-----
Currently, setting a job description (set to local properties) with multiple
threads does not properly work. Internally threads on PVM and JVM are not synced,
and JVM thread can be reused for multiple threads on PVM, which fails to isolate
local properties for each thread on PVM.

To avoid this, enable the pinned thread mode by setting ``PYSPARK_PIN_THREAD``
environment variable to ``true`` and uses :class:`pyspark.InheritableThread`.
If you run jobs in parallel, use :class:`pyspark.InheritableThread` for thread
local inheritance, and preventing resource leak.
"""
self._jsc.setJobDescription(value)

Expand Down
2 changes: 1 addition & 1 deletion python/pyspark/java_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def killChild():
atexit.register(killChild)

# Connect to the gateway (or client server to pin the thread between JVM and Python)
if os.environ.get("PYSPARK_PIN_THREAD", "false").lower() == "true":
if os.environ.get("PYSPARK_PIN_THREAD", "true").lower() == "true":
gateway = ClientServer(
java_parameters=JavaParameters(
port=gateway_port,
Expand Down
2 changes: 1 addition & 1 deletion python/pyspark/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
pickle_protocol = pickle.HIGHEST_PROTOCOL

from pyspark import cloudpickle
from pyspark.util import print_exec
from pyspark.util import print_exec # type: ignore


__all__ = ["PickleSerializer", "MarshalSerializer", "UTF8Deserializer"]
Expand Down
2 changes: 1 addition & 1 deletion python/pyspark/shuffle.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import heapq
from pyspark.serializers import BatchedSerializer, PickleSerializer, FlattenedValuesSerializer, \
CompressedSerializer, AutoBatchedSerializer
from pyspark.util import fail_on_stopiteration
from pyspark.util import fail_on_stopiteration # type: ignore


try:
Expand Down
2 changes: 1 addition & 1 deletion python/pyspark/tests/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def test_progress_api(self):
def run():
# When thread is pinned, job group should be set for each thread for now.
# Local properties seem not being inherited like Scala side does.
if os.environ.get("PYSPARK_PIN_THREAD", "false").lower() == "true":
if os.environ.get("PYSPARK_PIN_THREAD", "true").lower() == "true":
sc.setJobGroup('test_progress_api', '', True)
try:
rdd.count()
Expand Down
4 changes: 2 additions & 2 deletions python/pyspark/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,13 +276,13 @@ def inheritable_thread_target(f):

When the pinned thread mode is off, it return the original ``f``.

.. versionadded:: 3.2.0

Parameters
----------
f : function
the original thread target.

.. versionadded:: 3.2.0

Notes
-----
This API is experimental.
Expand Down
29 changes: 29 additions & 0 deletions python/pyspark/util.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import threading
from typing import Callable

class VersionUtils(object):
@staticmethod
def majorMinorVersion(sparkVersion: str): ...

def inheritable_thread_target(f: Callable) -> Callable: ...

class InheritableThread(threading.Thread):
pass
2 changes: 1 addition & 1 deletion python/pyspark/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
from pyspark.sql.pandas.serializers import ArrowStreamPandasUDFSerializer, CogroupUDFSerializer
from pyspark.sql.pandas.types import to_arrow_type
from pyspark.sql.types import StructType
from pyspark.util import fail_on_stopiteration, try_simplify_traceback
from pyspark.util import fail_on_stopiteration, try_simplify_traceback # type: ignore
from pyspark import shuffle

pickleSer = PickleSerializer()
Expand Down