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 6717b1ec [MINOR][CONNECT][TESTS] Keep the token out of the environment 
until the client tests connect, and skip the model releases of earlier tests in 
the requests that the ML tests check
6717b1ec is described below

commit 6717b1ec71ca12aad0801c698c2462bf4879d8bc
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 12:21:17 2026 +0900

    [MINOR][CONNECT][TESTS] Keep the token out of the environment until the 
client tests connect, and skip the model releases of earlier tests in the 
requests that the ML tests check
    
    ### What changes were proposed in this pull request?
    
    Two test-only fixes of flaky tests.
    
    - **Core client tests** (`crates/spark-connect-core/src/client.rs`): four 
tests removed `SPARK_CONNECT_AUTHENTICATE_TOKEN` from the environment only 
while they parsed their URL. They now keep it removed until 
`SparkConnectClient::connect` returns. The tests:
      - `recorded_client` of `request_fields_tests`;
      - `release_session_is_retried_on_unavailable_as_the_reference`;
      - `the_plan_that_a_hook_puts_in_is_compressed_as_pyspark`;
      - 
`requests_carry_the_client_type_extensions_and_observed_session_of_pyspark`.
    - **ML offline tests** (`python/tests/test_ml_offline.py`): the checks that 
read the command of an evaluate, a fit or a cache query by its position among 
the received requests now skip the Deletes of models that earlier tests 
released. They use two helpers next to `_requests_but_deletes`: 
`_commands_but_deletes` and `_last_request_but_deletes`.
    
    ### Why are the changes needed?
    
    - **The token race.** `connect` reads the token of the environment again 
(`ChannelBuilder::token`, through `secure()`). With a token there, a channel to 
`127.0.0.1` is TLS: as in PySpark, only `localhost` stays plaintext with a 
token. Tests that set a token run in parallel, and their guard can hold one in 
the environment while one of these tests connects. The client then speaks TLS 
to the plaintext test server, and its request fails with UNAVAILABLE `received 
corrupt message of type I [...]
    - **The Delete race.** A model that a test drops is released without 
waiting for it, so its Delete can reach the shared mock server during a later 
test, between that test's request and its check. 
`test_ml_connect_evaluators_take_the_signatures_and_defaults_of_pyspark` then 
read the Delete at the index of the evaluate, and failed once in a full run.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No, test-only.
    
    ### How was this patch tested?
    
    - With `SPARK_CONNECT_AUTHENTICATE_TOKEN=ENV` exported to the whole run, 
`cargo test -p apache-spark-connect-core --release --lib -- 
request_fields_tests:: 
release_session_is_retried_on_unavailable_as_the_reference`:
      - before: 3 of the 12 tests failed with `InvalidContentType`, after 611 s;
      - after: 12 passed in 0.01 s.
    - `python/tests/test_ml_offline.py`: 111 passed.
    - `cargo fmt --all --check` and `ruff check` are clean, and the trial of 
the merge runs every suite.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #542 from HyukjinKwon/s18c-deflake-tests.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect-core/src/client.rs | 39 +++++++++++++++++++--------------
 python/tests/test_ml_offline.py         | 37 +++++++++++++++++++++----------
 2 files changed, 48 insertions(+), 28 deletions(-)

diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index 655028c2..b41d33dc 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -3260,11 +3260,12 @@ mod tests {
                 .await
                 .unwrap();
         });
-        let builder = {
-            let _env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
-            ChannelBuilder::parse(&format!("sc://127.0.0.1:{}", 
address.port())).unwrap()
-        };
+        // `connect` reads the token of the environment too, so none is set 
until it returns:
+        // another test may set one, which would make the channel TLS.
+        let env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+        let builder = ChannelBuilder::parse(&format!("sc://127.0.0.1:{}", 
address.port())).unwrap();
         let mut client = SparkConnectClient::connect(&builder).await.unwrap();
+        drop(env);
         client.set_retry_policy(RetryPolicy {
             max_retries: Some(2),
             initial_backoff_ms: 1,
@@ -3819,11 +3820,13 @@ mod request_fields_tests {
                 .await
                 .unwrap();
         });
-        let builder = {
-            let _env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
-            ChannelBuilder::parse(&format!("sc://127.0.0.1:{}/", 
address.port())).unwrap()
-        };
+        // `connect` reads the token of the environment too, so none is set 
until it returns:
+        // another test may set one, which would make the channel TLS.
+        let env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+        let builder =
+            ChannelBuilder::parse(&format!("sc://127.0.0.1:{}/", 
address.port())).unwrap();
         let client = SparkConnectClient::connect(&builder).await.unwrap();
+        drop(env);
         *client.plan_compression.lock().unwrap() = PlanCompression::Zstd { 
threshold: 1000 };
         let large = spark_connect_proto::Relation {
             rel_type: 
Some(spark_connect_proto::relation::RelType::LocalRelation(
@@ -3884,12 +3887,14 @@ mod request_fields_tests {
                 .await
                 .unwrap();
         });
-        let builder = {
-            let _env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+        // `connect` reads the token of the environment too, so none is set 
until it returns:
+        // another test may set one, which would make the channel TLS.
+        let env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+        let builder =
             ChannelBuilder::parse(&format!("sc://127.0.0.1:{}/;user_id=u1", 
address.port()))
-                .unwrap()
-        };
+                .unwrap();
         let client = SparkConnectClient::connect(&builder).await.unwrap();
+        drop(env);
         let session_id = client.session_id().to_string();
         let extension = prost_types::Any {
             type_url: "example.org/context".into(),
@@ -4031,12 +4036,14 @@ mod request_fields_tests {
                 .await
                 .unwrap();
         });
-        let builder = {
-            let _env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+        // `connect` reads the token of the environment too, so none is set 
until it returns:
+        // another test may set one, which would make the channel TLS.
+        let env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+        let builder =
             ChannelBuilder::parse(&format!("sc://127.0.0.1:{}/;user_id=u1", 
address.port()))
-                .unwrap()
-        };
+                .unwrap();
         let client = SparkConnectClient::connect(&builder).await.unwrap();
+        drop(env);
         (client, received, server)
     }
 
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 7f16a692..8c9d4439 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -111,6 +111,19 @@ def _requests_but_deletes(service):
     return sum(not command.ml_command.HasField("delete") for command in 
_commands(service))
 
 
+def _commands_but_deletes(service, start=0):
+    # The commands of the requests that the server received from the start-th 
on, but the
+    # Deletes of models that earlier tests released: a release is sent without 
waiting for it,
+    # so it can reach the server between a request of a test and the check of 
that request.
+    return [c for c in _commands(service)[start:] if not 
c.ml_command.HasField("delete")]
+
+
+def _last_request_but_deletes(service):
+    # The last ExecutePlanRequest that the server received, but such a Delete.
+    requests = map(pb2.ExecutePlanRequest.FromString, service.execute_requests)
+    return [r for r in requests if not 
r.plan.command.ml_command.HasField("delete")][-1]
+
+
 def _relation(df):
     # The relation of a DataFrame, as the core sends it: the relation that the 
plans of pyspark.ml
     # send in place of its placeholder, which the core replaces with it.
@@ -143,7 +156,7 @@ def test_ml_cache_queries_are_those_of_pyspark(ml_mock):
 
     service.execute_payload = _ml_result(param=pb2.Expression.Literal(long=42))
     assert client._query_model_size("ref-1") == 42
-    command = _commands(service)[-1]
+    command = _commands_but_deletes(service)[-1]
     assert command.ml_command.get_model_size.model_ref == 
pb2.ObjectRef(id="ref-1")
 
 
@@ -165,7 +178,7 @@ def 
test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
         service.execute_payload = _operator_info("model-1")
         estimator = cls(inputCol=column, outputCol="o")
         models.append(estimator.fit(df))
-        fit = _commands(service)[sent].ml_command.fit
+        fit = _commands_but_deletes(service, sent)[0].ml_command.fit
         assert fit.estimator.name == name
         assert fit.estimator.type == pb2.MlOperator.OPERATOR_TYPE_ESTIMATOR
         assert dict(fit.params.params) == {
@@ -218,11 +231,11 @@ def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
         if hasattr(obj, "evaluate"):
             service.execute_payload = 
_ml_result(param=pb2.Expression.Literal(double=0.5))
             assert obj.evaluate(df) == 0.5
-            params = _commands(service)[sent].ml_command.evaluate.params
+            params = _commands_but_deletes(service, 
sent)[0].ml_command.evaluate.params
         elif hasattr(obj, "fit"):
             service.execute_payload = _operator_info("model-1")
             models.append(obj.fit(df))
-            params = _commands(service)[sent].ml_command.fit.params
+            params = _commands_but_deletes(service, 
sent)[0].ml_command.fit.params
         else:
             params = _relation(obj.transform(df)).ml_relation.transform.params
         return {name: value(literal) for name, literal in 
params.params.items()}
@@ -412,12 +425,12 @@ def _native_request(spark, service, obj, models):
     if hasattr(obj, "evaluate"):
         service.execute_payload = 
_ml_result(param=pb2.Expression.Literal(double=0.5))
         assert obj.evaluate(df) == 0.5
-        evaluate = _commands(service)[sent].ml_command.evaluate
+        evaluate = _commands_but_deletes(service, sent)[0].ml_command.evaluate
         return evaluate.evaluator, evaluate.params
     if hasattr(obj, "fit"):
         service.execute_payload = _operator_info("model-1")
         models.append(obj.fit(df))
-        fit = _commands(service)[sent].ml_command.fit
+        fit = _commands_but_deletes(service, sent)[0].ml_command.fit
         return fit.estimator, fit.params
     transform = _relation(obj.transform(df)).ml_relation.transform
     return transform.transformer, transform.params
@@ -1108,7 +1121,7 @@ def 
test_user_context_extensions_are_sent_as_pyspark(ml_mock):
     command = pb2.Command()
     command.ml_command.clean_cache.SetInParent()
     client.execute_command(command)
-    request = pb2.ExecutePlanRequest.FromString(service.execute_requests[-1])
+    request = _last_request_but_deletes(service)
     assert list(request.user_context.extensions) == [packed("global"), 
packed("local")]
     assert spark.range(1).schema is not None
     analysis = pb2.AnalyzePlanRequest.FromString(service.analyze_requests[-1])
@@ -1125,7 +1138,7 @@ def 
test_user_context_extensions_are_sent_as_pyspark(ml_mock):
     thread.start()
     thread.join()
     assert seen == [[]]
-    request = pb2.ExecutePlanRequest.FromString(service.execute_requests[-1])
+    request = _last_request_but_deletes(service)
     assert list(request.user_context.extensions) == [packed("global")]
 
     client.remove_user_context_extension(local)
@@ -1133,7 +1146,7 @@ def 
test_user_context_extensions_are_sent_as_pyspark(ml_mock):
     client.clear_user_context_extensions()
     assert client.global_user_context_extensions == []
     client.execute_command(command)
-    request = pb2.ExecutePlanRequest.FromString(service.execute_requests[-1])
+    request = _last_request_but_deletes(service)
     assert list(request.user_context.extensions) == []
 
 
@@ -1249,7 +1262,7 @@ def 
test_ml_execute_command_returns_the_results_of_pyspark(ml_mock):
     assert data is None and info is None
     assert list(properties) == ["ml_command_result"]
     assert properties["ml_command_result"].operator_info.obj_ref.id == "ref-1"
-    request = pb2.ExecutePlanRequest.FromString(service.execute_requests[-1])
+    request = _last_request_but_deletes(service)
     assert request.session_id == spark.session_id
     assert request.plan.command == command
 
@@ -1275,7 +1288,7 @@ def test_ml_cache_commands_are_those_of_pyspark(ml_mock):
     assert client._delete_ml_cache([]) == []
     assert len(service.execute_requests) == 1
     client._cleanup_ml_cache()
-    assert _commands(service)[-1].ml_command.HasField("clean_cache")
+    assert 
_commands_but_deletes(service)[-1].ml_command.HasField("clean_cache")
     service.execute_failure = "the server failed"
     assert client._delete_ml_cache(["c"]) == []
     client._cleanup_ml_cache()
@@ -2308,7 +2321,7 @@ def 
test_session_hooks_rewrite_the_requests_of_executions_as_pyspark(_ml_mock_se
         command = pb2.Command()
         command.ml_command.clean_cache.SetInParent()
         spark.client.execute_command(command)
-        request = 
pb2.ExecutePlanRequest.FromString(service.execute_requests[-1])
+        request = _last_request_but_deletes(service)
         assert list(request.tags)[-2:] == ["first", "second"]
         assert request.operation_id == created[0].operation_ids[0]
         assert created[1].operation_ids == created[0].operation_ids


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

Reply via email to