This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 4305ae03 [SPARK-61235][CONNECT][PYTHON] Add the 
pyspark.sql.connect.resource.profile module and the DistributedSequenceID and 
UnresolvedNamedLambdaVariable expressions of PySpark Connect
4305ae03 is described below

commit 4305ae03267bfd43d1ea6cb21a569344b6635db3
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 21:35:02 2026 +0900

    [SPARK-61235][CONNECT][PYTHON] Add the pyspark.sql.connect.resource.profile 
module and the DistributedSequenceID and UnresolvedNamedLambdaVariable 
expressions of PySpark Connect
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61235](https://issues.apache.org/jira/browse/SPARK-61235): Add the 
`pyspark.sql.connect.resource.profile` module and the `DistributedSequenceID` 
and `UnresolvedNamedLambdaVariable` expressions of 
`pyspark.sql.connect.expressions`, as PySpark 4.3.0 has them.
    
    - `pyspark/sql/connect/resource/profile.py` re-exports `ResourceProfile` 
from `pyspark.resource`, as the Connect package already does for the other 
resource classes. The profile id is the server's already: `ResourceProfile.id` 
registers the profile through `SparkSession.buildResourceProfile` and caches 
the server's id, as PySpark's Connect path does.
    - `pyspark/sql/connect/expressions.py` gets `DistributedSequenceID`, whose 
`to_plan` is an unresolved function `distributed_sequence_id` with no 
arguments, and `UnresolvedNamedLambdaVariable`, with the class counter 
`_nextVarNameId`, `fresh_var_name`, and a `to_plan` of its name parts. Both 
give the same proto and `repr` as PySpark 4.3.0.
    - `pyspark/sql/functions.py` names the lambda variables with 
`UnresolvedNamedLambdaVariable.fresh_var_name`, so resetting its counter 
changes the names of the lambdas of the connect functions, as in PySpark.
    
    ### Why are the changes needed?
    
    `from pyspark.sql.connect.resource.profile import ResourceProfile` raised 
`ModuleNotFoundError`. `from pyspark.sql.connect.expressions import 
DistributedSequenceID` raised `ImportError`, so the official 
`pyspark/sql/tests/connect/test_connect_column.py` failed at collection. 
Official PySpark 4.3.0 imports both.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. The two imports above work, and the expressions are available under 
`pyspark.sql.connect.expressions`.
    
    ### How was this patch tested?
    
    - `test_connect_resource_profile_module_offline` checks that the module's 
`ResourceProfile` is the `pyspark.resource` class. It fails without the change 
(`ModuleNotFoundError`).
    - 
`test_connect_expressions_distributed_sequence_id_and_lambda_names_offline` 
checks the repr and proto of `DistributedSequenceID` and 
`UnresolvedNamedLambdaVariable`, and the lambda names after a counter reset. It 
fails without the change (`ImportError`). The same cases give the same results 
with official PySpark 4.3.0 (`DistributedSequenceID()`, 
`distributed_sequence_id`, `x, y`, `Column<'array_sort(data, 
LambdaFunction(-(length(x_0), length(y_1)), x_0, y_1))'>`, `z_2`).
    - The official `test_connect_column.py` now imports (it is skipped by the 
class gate `ReusedMixedTestCase`, as on the reference). The official 
`test_connect_resources.py` and `test_parity_resources.py` pass.
    - The live tests of the resource and higher-order function areas (`-k 
"resource or profile or lambda or transform or higher or array_sort"`) pass.
    - The lib tests of both crates (664 passed), the build of all tests, also 
with `wasm-udf`, the offline Python suites (2821 passed, 8 skipped), and the 
live drop-in and Arrow suites (233 passed) and live cases (13 passed) against a 
local Spark 4.3.0 server. Clippy reports no diagnostics in the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #416 from HyukjinKwon/SPARK-61235-connect-modules.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 python/pyspark/sql/connect/expressions.py      | 55 ++++++++++++++++++++++++++
 python/pyspark/sql/connect/resource/profile.py | 27 +++++++++++++
 python/pyspark/sql/functions.py                | 11 ++----
 python/tests/test_dropin_offline.py            | 33 ++++++++++++++++
 4 files changed, 119 insertions(+), 7 deletions(-)

diff --git a/python/pyspark/sql/connect/expressions.py 
b/python/pyspark/sql/connect/expressions.py
index 5338405b..42b9560a 100644
--- a/python/pyspark/sql/connect/expressions.py
+++ b/python/pyspark/sql/connect/expressions.py
@@ -35,6 +35,7 @@ from typing import (
 
 import decimal
 import datetime
+from threading import Lock
 
 import numpy as np
 
@@ -454,3 +455,57 @@ class LiteralExpression(Expression):
                 # while Pandas applies all supported units.
                 return pd.Timedelta(delta).isoformat()
         return f"{self._value}"
+
+
+class UnresolvedNamedLambdaVariable(Expression):
+    """A variable of a lambda function, of the name parts of a column 
reference. The lambda
+    functions of ``pyspark.sql.functions`` name their variables with 
:meth:`fresh_var_name`."""
+
+    _lock: Lock = Lock()
+    _nextVarNameId: int = 0
+
+    def __init__(
+        self,
+        name_parts: Sequence[str],
+    ) -> None:
+        super().__init__()
+
+        assert (
+            isinstance(name_parts, list)
+            and len(name_parts) > 0
+            and all(isinstance(p, str) for p in name_parts)
+        )
+
+        self._name_parts = name_parts
+
+    def to_plan(self, session: Any) -> "proto.Expression":
+        expr = self._create_proto_expression()
+        
expr.unresolved_named_lambda_variable.name_parts.extend(self._name_parts)
+        return expr
+
+    def __repr__(self) -> str:
+        return ", ".join(self._name_parts)
+
+    @staticmethod
+    def fresh_var_name(name: str) -> str:
+        assert isinstance(name, str) and name != ""
+
+        with UnresolvedNamedLambdaVariable._lock:
+            _id = UnresolvedNamedLambdaVariable._nextVarNameId
+            UnresolvedNamedLambdaVariable._nextVarNameId += 1
+
+        return f"{name}_{_id}"
+
+
+class DistributedSequenceID(Expression):
+    """The ``distributed_sequence_id()`` function, which the server 
evaluates."""
+
+    def to_plan(self, session: Any) -> "proto.Expression":
+        # As PySpark's UnresolvedFunction of no argument, which is not 
distinct.
+        expr = self._create_proto_expression()
+        expr.unresolved_function.function_name = "distributed_sequence_id"
+        expr.unresolved_function.is_distinct = False
+        return expr
+
+    def __repr__(self) -> str:
+        return "DistributedSequenceID()"
diff --git a/python/pyspark/sql/connect/resource/profile.py 
b/python/pyspark/sql/connect/resource/profile.py
new file mode 100644
index 00000000..4e13362b
--- /dev/null
+++ b/python/pyspark/sql/connect/resource/profile.py
@@ -0,0 +1,27 @@
+#
+# 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.
+#
+
+"""Compatibility shim for pyspark.sql.connect.resource.profile.
+
+PySpark Connect's ResourceProfile registers the profile on the server and 
keeps the server's
+profile id. Here ``pyspark.resource.ResourceProfile`` does that on its ``id`` 
property, through the
+Rust transport (``SparkSession.buildResourceProfile``), so this module 
re-exports it.
+"""
+
+from pyspark.resource.profile import ResourceProfile
+
+__all__ = ["ResourceProfile"]
diff --git a/python/pyspark/sql/functions.py b/python/pyspark/sql/functions.py
index 7862cde7..8d9442b1 100644
--- a/python/pyspark/sql/functions.py
+++ b/python/pyspark/sql/functions.py
@@ -508,14 +508,11 @@ _call_named_function = 
_functions.pyfunc_call_named_function
 # dispatch allowlist). Mirrors pyspark.sql.connect.functions._invoke_function.
 _invoke_function = _functions.pyfunc_invoke_function
 
-# Global monotonic counter, mirroring 
UnresolvedNamedLambdaVariable._nextVarNameId.
-_lambda_var_name_id = [0]
-
-
 def _fresh_lambda_var_name(name):
-    _id = _lambda_var_name_id[0]
-    _lambda_var_name_id[0] += 1
-    return f"{name}_{_id}"
+    # The counter of UnresolvedNamedLambdaVariable, as PySpark Connect's, 
which a test resets.
+    from pyspark.sql.connect.expressions import UnresolvedNamedLambdaVariable
+
+    return UnresolvedNamedLambdaVariable.fresh_var_name(name)
 
 
 def _get_lambda_parameters(f):
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index dba74b8d..8d7fb8ad 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -41,6 +41,39 @@ from interval_input_cases import 
IntervalInputConversionTests  # noqa: F401
 from streaming_listener_cases import TestStreamingListenerLifecycle  # noqa: 
F401
 
 
+def 
test_connect_expressions_distributed_sequence_id_and_lambda_names_offline():
+    # The expressions that the official test_connect_column imports: 
DistributedSequenceID, and
+    # UnresolvedNamedLambdaVariable, whose counter names the lambda variables, 
as PySpark's does.
+    from pyspark.sql.connect import functions as CF
+    from pyspark.sql.connect.expressions import DistributedSequenceID, 
UnresolvedNamedLambdaVariable
+
+    assert repr(DistributedSequenceID()) == "DistributedSequenceID()"
+    plan = DistributedSequenceID().to_plan(None)
+    assert plan.unresolved_function.function_name == "distributed_sequence_id"
+    assert not plan.unresolved_function.is_distinct
+    assert len(plan.unresolved_function.arguments) == 0
+
+    var = UnresolvedNamedLambdaVariable(["x", "y"])
+    assert repr(var) == "x, y"
+    assert list(var.to_plan(None).unresolved_named_lambda_variable.name_parts) 
== ["x", "y"]
+
+    UnresolvedNamedLambdaVariable._nextVarNameId = 0
+    c = CF.array_sort("data", lambda x, y: CF.length(x) - CF.length(y))
+    assert str(c) == (
+        "Column<'array_sort(data, LambdaFunction(-(length(x_0), length(y_1)), 
x_0, y_1))'>"
+    )
+    assert UnresolvedNamedLambdaVariable.fresh_var_name("z") == "z_2"
+
+
+def test_connect_resource_profile_module_offline():
+    # PySpark Connect's module of ResourceProfile, which the client packages 
ship; the profile id
+    # that `ResourceProfile.id` gives is the server's, as PySpark's is.
+    from pyspark.sql.connect.resource.profile import ResourceProfile
+    from pyspark.resource import ResourceProfile as ClientResourceProfile
+
+    assert ResourceProfile is ClientResourceProfile
+
+
 def test_create_dataframe_input_names_offline():
     # Keep the fixture's active session out of this process's offline tests.
     import subprocess


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to