@@ -472,6 +472,28 @@ def create_session_pbar():
472472 session_response , dataproc_config .name
473473 )
474474
475+ # def _wait_for_spark_connect_endpoint(
476+ # self, session_name: str, timeout: int = 300
477+ # ) -> Session:
478+ # """Waits for the Spark Connect endpoint to be available in the session."""
479+ # start_time = time.time()
480+ # while time.time() - start_time < timeout:
481+ # try:
482+ # session = self.session_controller_client.get_session(
483+ # name=session_name
484+ # )
485+ # if "Spark Connect Server" in session.runtime_info.endpoints:
486+ # return session
487+ # time.sleep(5)
488+ # except Exception as e:
489+ # logger.warning(
490+ # f"Error while polling for Spark Connect endpoint: {e}"
491+ # )
492+ # time.sleep(5)
493+ # raise RuntimeError(
494+ # f"Spark Connect endpoint not available for session {session_name} after {timeout} seconds."
495+ # )
496+
475497 def _display_session_link_on_creation (self , session_id ):
476498 session_url = f"https://console.cloud.google.com/dataproc/interactive/{ self ._region } /{ session_id } ?project={ self ._project_id } "
477499 plain_message = f"Creating Dataproc Session: { session_url } "
@@ -537,6 +559,10 @@ def _get_exiting_active_session(
537559 )
538560 self ._display_view_session_details_button (s8s_session_id )
539561 if session is None :
562+ # Wait for the Spark Connect endpoint to be available
563+ # session_response = self._wait_for_spark_connect_endpoint(
564+ # session_name
565+ # )
540566 session = self .__create_spark_connect_session_from_s8s (
541567 session_response , session_name
542568 )
@@ -559,6 +585,13 @@ def getOrCreate(self) -> "DataprocSparkSession":
559585 session = self ._get_exiting_active_session ()
560586 if session is None :
561587 session = self .__create ()
588+
589+ # Register this session as the instantiated SparkSession for compatibility
590+ # with tools and libraries that expect SparkSession._instantiatedSession
591+ from pyspark .sql import SparkSession as PySparkSQLSession
592+
593+ PySparkSQLSession ._instantiatedSession = session
594+
562595 return session
563596
564597 def _handle_custom_session_id (self ):
@@ -1162,6 +1195,20 @@ def stop(self) -> None:
11621195 )
11631196
11641197 self ._remove_stopped_session_from_file ()
1198+
1199+ # Clean up SparkSession._instantiatedSession if it points to this session
1200+ try :
1201+ from pyspark .sql import SparkSession as PySparkSQLSession
1202+
1203+ if PySparkSQLSession ._instantiatedSession is self :
1204+ PySparkSQLSession ._instantiatedSession = None
1205+ logger .debug (
1206+ "Cleared SparkSession._instantiatedSession reference"
1207+ )
1208+ except (ImportError , AttributeError ):
1209+ # PySpark not available or _instantiatedSession doesn't exist
1210+ pass
1211+
11651212 DataprocSparkSession ._active_s8s_session_uuid = None
11661213 DataprocSparkSession ._active_s8s_session_id = None
11671214 DataprocSparkSession ._active_session_uses_custom_id = False
0 commit comments