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 8ddbf24e [SPARK-61217][CONNECT][RUST] Support independent Python 
DataFrame subclasses
8ddbf24e is described below

commit 8ddbf24e6dd2dbd718700513064e70716f7e21e3
Author: DB Tsai <[email protected]>
AuthorDate: Mon Nov 9 15:51:53 2026 +0900

    [SPARK-61217][CONNECT][RUST] Support independent Python DataFrame subclasses
    
    ### What changes were proposed in this pull request?
    
    Provide a Python public `pyspark.sql.DataFrame` base/factory so independent 
subclasses can initialize Python-owned state and override operations. Ordinary 
construction returns the concrete native Connect frame. Public calls dispatch 
to the current concrete implementation, and removing temporary public-class 
overrides restores the prior concrete state. Preserve public-base fallbacks and 
add subclass, dispatch, restoration and annotation regression coverage.
    
    ### Why are the changes needed?
    
    The public class currently reexports the native allocator. Official 
PySpark's `MockDataset` allocates a Python subclass with `object.__new__(cls)`, 
which raises `TypeError` with that allocator before its initializer runs. The 
official pipeline tests depend on this pattern.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. This example can initialize the subclass's own state:
    
    ```python
    from pyspark.testing.mlutils import MockDataset
    
    assert MockDataset().index == 0
    ```
    
    The native concrete class has virtual public-base membership; its actual 
MRO remains native, so `super(DataFrame, native_frame)` is unsupported. Direct 
native subclasses must initialize their native payload through its constructor. 
The public base uses an `ABCMeta` subclass; ordinary Python subclasses use 
standard `abc.ABCMeta`, while unrelated metaclasses require a combined 
metaclass. Public and Connect `Column` aliases are the same native object, 
although its advertised module metad [...]
    
    ### How was this patch tested?
    
    - On the final helper-name/comment revision, this selection passed **13 
cases**, with 81 deselected and no skips, failures or errors:
    
      ```bash
      python -m pytest -q --rootdir=python --import-mode=importlib \
        python/tests/test_ml_offline.py \
        -k 'public_dataframe or python_dataframe_subclass or 
local_dataframe_subclasses_cloudpickle'
      ```
    
      Pytest exited 0. The outer harness exited 1 because it incorrectly 
expected at least 22 cases from this narrower selection; that counting failure 
was retained and assessed separately.
    - Before those two private-helper renames and comment changes, the full 
offline selection passed **2,676 Python tests**, including all **22 required 
subclass cases** and the new annotation assertions; eight separate live-server 
cases skipped. Those results carry forward as historical executions: reversing 
the private-helper renames produces the same AST, and all other source, tests, 
compiled inputs and the extension are unchanged.
    - Historical checks on identical Rust/build inputs passed 141 core Rust 
tests, 495 API Rust tests, formatting, extension build, all-test compilation 
and wasm-udf test compilation. These were verified and carried forward rather 
than rerun. Advisory workspace/all-target Clippy exited **101** at source sites 
assessed as inherited; a clean lint result is not claimed.
    - The unchanged 20-case official pipeline/tuning/one-vs-rest selection 
passed on both official and native high-level clients under predeclared 
`PYTHONHASHSEED=0`: **16 passed / four upstream-disabled GC skips each**, 
including `test_pipeline` and `test_identity_pipeline`. This is bounded 
historical evidence. An earlier default-hash native Random Forest 
cross-validation run failed on a one-class training fold; the failure is 
retained and its cause remains unproven.
    - The artifact independently ran official high-level PySpark through its 
Rust transport plugin: **39 passed / five skipped** across configuration, 
DataFrame creation, pipeline, tuning and one-vs-rest. Configuration/creation 
accounted for 23 passes and one skip; ML accounted for 16 passes and four GC 
skips. This transport execution is distinct from the native high-level ML 
selection above and predates only the private-helper renames/comments.
    - The third cloudpickle probe passed on the source before those 
renames/comments: an ordinary local subclass and captured closure were 
reconstructed and exercised in an official-only consumer without native 
imports. This coverage excludes independent instances, explicit user 
metaclasses, native DataFrame serialization and server UDFs.
    - API assessment covered all **500 canonical mismatch records / 171 
controlled fields**, plus 12 central API groups and the Row-name gate. Getter 
parameter annotations now match official PySpark, and tests verify the return 
annotation is the public/Connect `Column` object. The raw comparison exited 1 
for assessed differences; public/concrete name inventories have no missing 
public names. Native MRO, metaclass, factory, inherited-signature and `Column` 
module-metadata limits remain visible.
    - Shared transport evidence was completed on a separate artifact with the 
same **53 transport/build/dependency inputs**: 87 ordinary modules recorded 
2,586 passes, 641 skips, one manifest deselection and one retained expected 
catalog-drift failure; four separate cluster modules recorded 15 passes and 14 
skips. No unexpected failures remained. This candidate carries that 
common-source evidence and executed its own plugin checks above; it did not 
execute those full suites. Source equali [...]
    
    Final independent full-patch review completed with no remaining findings. 
All earlier findings and fixes, including the final helper-name and comment 
changes, were assessed. The execution boundaries and retained failures above 
remain part of the validation record.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: OpenAI Codex
    
    This pull request and its description were written by OpenAI Codex.
    
    Closes #400 from dbtsai/codex/residual-dataframe-subclass-master-0ac7a0f.
    
    Lead-authored-by: DB Tsai <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs  |  14 +-
 dev/parity/known-differences.md     |  87 +++-
 python/pyspark/sql/dataframe.py     | 313 +++++++++++++-
 python/tests/test_dropin_offline.py |  30 +-
 python/tests/test_ml_offline.py     | 783 ++++++++++++++++++++++++++++++++++++
 5 files changed, 1205 insertions(+), 22 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index f47a4688..bc2a5aa1 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2114,9 +2114,10 @@ impl PyDataFrame {
         Ok(slf)
     }
 
-    /// Column access by attribute (`df.colname` -> Column), mirroring 
reference pyspark: the
-    /// column of this DataFrame, by its plan ID. Names beginning with `_` 
raise
-    /// AttributeError so normal attribute lookup works.
+    /// Column access by attribute (`df.colname` -> Column), by this 
DataFrame's plan ID.
+    /// JVM attribute names raise JVM_ATTRIBUTE_NOT_SUPPORTED. Dunder names 
that are not
+    /// columns raise ATTRIBUTE_NOT_SUPPORTED; with 
PYSPARK_VALIDATE_COLUMN_NAME_LEGACY=1,
+    /// all non-column names do. Single-underscore names otherwise resolve to 
columns.
     fn __getattr__(&self, py: Python<'_>, name: &str) -> PyResult<PyColumn> {
         // As PySpark Connect's: the attributes of the JVM of a classic 
DataFrame are not
         // supported, and a name is validated as a column only for a dunder 
name, which Python
@@ -2141,6 +2142,13 @@ impl PyDataFrame {
         Ok(PyColumn::new(self.dataframe.col(name)))
     }
 
+    /// Private bridge used by pyspark.sql.dataframe.DataFrame.__getattr__ for
+    /// explicit column lookup. The __getattr__ special method itself is 
exposed
+    /// only as a slot; this ordinary method remains callable by the public 
base.
+    fn _get_column_by_attribute(&self, py: Python<'_>, name: &str) -> 
PyResult<PyColumn> {
+        self.__getattr__(py, name)
+    }
+
     /// Class attributes and all column names, matching Python Connect.
     fn __dir__(&self, py: Python<'_>) -> PyResult<Vec<String>> {
         // Inspect the class rather than the instance to avoid calling __dir__ 
again.
diff --git a/dev/parity/known-differences.md b/dev/parity/known-differences.md
index c6ae7a3d..138d8473 100644
--- a/dev/parity/known-differences.md
+++ b/dev/parity/known-differences.md
@@ -70,11 +70,82 @@ difference is intentional or tracked for a fix.
 
 ## `DataFrame`
 
-- **A subclass of `DataFrame` created with `object.__new__`** (intentional, a 
PyO3 limit).
-  `DataFrame` is a class of the Rust extension, so `object.__new__(cls)` of a 
subclass raises
-  `TypeError: object.__new__(cls) is not safe`. `MockDataset` of 
`pyspark.testing.mlutils`
-  creates itself so, and two of Apache Spark's ML parity tests that use it
-  (`test_parity_pipeline.py`'s `test_pipeline` and `test_identity_pipeline`) 
fail for that
-  reason only. The rest of `pyspark/ml/tests/connect/test_parity_*.py` pass 
with this client,
-  except for a test that reads `data/mllib` of the Spark source tree from the 
working directory
-  of the server.
+- **Public base and native MRO.** `pyspark.sql.DataFrame` is implemented as a
+  Python base/factory, allowing subclasses such as
+  `pyspark.testing.mlutils.MockDataset` to allocate their own Python state with
+  `object.__new__`. The concrete class remains
+  `pyspark.sql.connect.dataframe.DataFrame`, implemented by the Rust 
extension. It is
+  registered as a virtual subclass of the public base: `isinstance` and 
`issubclass`
+  recognize it, while its actual MRO stays native. Consequently, `super` and 
MRO
+  introspection do not treat a native frame as inheriting from the public base.
+
+- **Metaclass and subclass serialization.** The public base uses an `ABCMeta`
+  subclass for virtual registration and attribute forwarding, while official
+  PySpark uses `type`. It exposes `register()`, and
+  multiple inheritance with an unrelated metaclass requires a combined 
metaclass.
+  Ordinary Python subclasses use the standard `abc.ABCMeta` so by-value
+  cloudpickling names an importable metaclass on official Python workers. 
Explicit
+  user metaclass subclasses are preserved and retain their own serialization
+  requirements. A local subclass and a closure capturing that subclass were
+  cloudpickled by the native client and reconstructed and exercised in an
+  official-only Python process without importing the native extension. This 
does
+  not establish portability of instances, explicit user metaclasses or server 
UDFs.
+
+- **Public class mutation and dispatch.** Public-base method and property calls
+  look up the concrete implementation at call time, including concrete-class
+  patches made after import. Assigning or deleting user extensions directly on 
the
+  public class also updates the native class, so added helpers and overridden
+  methods reach existing native frames;
+  assignments on Python subclasses remain local to those subclasses.
+  Deleting an initial public method or property removes its public-base 
exposure
+  and restores the concrete implementation that preceded a public override, 
while
+  preserving any later independent concrete patch. Deleting an added
+  helper removes the forwarded helper; deleting a temporary extension that 
shadows
+  a native-only attribute restores that native attribute.
+  Class layout, constructor, import/ABC metadata and instance attribute 
protocols
+  `__getattribute__`, `__setattr__` and `__delattr__` stay on the public base. 
Those
+  protocols follow ordinary Python inheritance on independent subclasses; 
virtual
+  native membership does not inherit them.
+
+- **Attribute resolution.** Explicit public `__getattr__` calls use the native
+  column resolver, including existing attribute names, unsupported JVM names, 
and
+  dunder/legacy column validation. While a user override of public 
`__getattr__`
+  is active, native frames use generic Python attribute lookup before calling 
that
+  hook. Undo restores the saved native lookup entry and prior hook state, 
including
+  absence of a native `__getattr__` entry. Importing the public base does not 
alter
+  the native lookup entries. The native-only private method
+  `_get_column_by_attribute` bridges explicit public lookup to the Rust 
resolver;
+  it is an intentional extra name in concrete-class introspection and 
completion.
+
+- **Independent Python subclasses and construction.** Python subclasses 
override
+  operations for their own data model. As in PySpark, inherited public 
properties
+  read `None`, while native-dispatched methods,
+  including `repr`, `dir`, and missing-attribute `__getattr__`, raise
+  `NOT_IMPLEMENTED` on independent Python data. Consequently, `hasattr` for an
+  unknown name also raises that exception, including on `MockDataset`.
+  The official undecorated empty methods `checkpoint`, `localCheckpoint`,
+  `lateralJoin`, `nearestByJoin`, `toPandas`, `asTable`, `scalar` and `exists` 
return
+  `None` after argument binding. The inherited `__arrow_c_stream__` uses the
+  generic `SparkArrowCStreamer` helper with the independent frame and requested
+  schema, as on the official public base.
+  Internal `_session` and `_plan` remain ordinary instance state on those 
subclasses.
+  `is_cached` is an annotation and assignable instance state, as on the 
official
+  public base. Concrete getters for these names are not installed as public
+  properties.
+  A public-base subclass that inherits the factory's `__new__` receives a plain
+  concrete frame, and its own `__init__` is not called. Define `__new__` using
+  `object.__new__` for independent Python data, or subclass
+  `pyspark.sql.connect.dataframe.DataFrame` for native-backed subclass 
behavior.
+  A direct native subclass must use the native constructor to initialize its 
Rust
+  payload; `object.__new__` cannot safely allocate that payload.
+
+- **Validation status.** All 22 subclass cases passed in the native offline 
suite.
+  The unchanged official pipeline, tuning and one-vs-rest selection passed on 
both
+  the official and native high-level clients with `PYTHONHASHSEED=0`: 16 
passed and
+  four upstream-disabled GC tests skipped on each client. This includes
+  `test_pipeline` and `test_identity_pipeline`. An earlier run with independent
+  default Python hash seeds failed native Random Forest cross-validation on a
+  one-class training fold; that failure is retained, and its cause is not 
proven
+  by the fixed-hash passes. API inspection records the public-base and
+  concrete-class differences; inherited signature and annotation differences 
remain.
+  These results do not establish complete DataFrame or ML parity.
diff --git a/python/pyspark/sql/dataframe.py b/python/pyspark/sql/dataframe.py
index b26c9f60..3450302d 100644
--- a/python/pyspark/sql/dataframe.py
+++ b/python/pyspark/sql/dataframe.py
@@ -14,6 +14,315 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
-"""Re-export of the Rust-backed class(es) under the official pyspark.sql 
import path."""
-from pyspark._pyspark import DataFrame, DataFrameNaFunctions, 
DataFrameStatFunctions
+"""The public DataFrame base and its concrete Rust-backed implementation.
+
+As in PySpark, ``pyspark.sql.DataFrame`` is a Python base/factory, whereas
+``pyspark.sql.connect.dataframe.DataFrame`` is the concrete remote DataFrame.  
Keeping
+the public base in Python lets user-defined subclasses allocate their own 
Python state
+with ``object.__new__``.  A concrete frame must still be allocated by the 
native class:
+its Rust payload cannot be initialized by Python's object allocator.
+"""
+
+from abc import ABCMeta
+from functools import wraps
+from inspect import signature
+from types import (
+    ClassMethodDescriptorType,
+    FunctionType,
+    GetSetDescriptorType,
+    MethodDescriptorType,
+    WrapperDescriptorType,
+)
+from typing import NamedTuple
+
+from pyspark._pyspark import (
+    Column,
+    DataFrame as _NativeDataFrame,
+    DataFrameNaFunctions,
+    DataFrameStatFunctions,
+)
+
 __all__ = ["DataFrame", "DataFrameNaFunctions", "DataFrameStatFunctions"]
+
+_public_dataframe = None
+_initial_public_attributes = {}
+_native_overrides = {}
+_missing = object()
+
+# The undecorated, empty-bodied public methods in official PySpark 4.3.0
+# pyspark/sql/dataframe.py. Re-derive this list on every PySpark version bump.
+# They return None on independent Python subclasses instead of native dispatch.
+_empty_public_methods = frozenset({
+    "checkpoint", "localCheckpoint", "lateralJoin", "nearestByJoin", 
"toPandas",
+    "asTable", "scalar", "exists",
+})
+
+
+class _NativeOverride(NamedTuple):
+    previous_native: object
+    forwarded: object
+    previous_lookup: object
+
+
+# These describe the Python class's layout, instance attribute protocols or
+# import/ABC bookkeeping. They belong to the public base and must not overwrite
+# the concrete type's own behavior or metadata.
+_local_class_attributes = frozenset({
+    "__new__", "__init__", "__name__", "__module__", "__qualname__", 
"__doc__", "__dict__",
+    "__weakref__", "__bases__", "__base__", "__mro__", "__slots__", 
"__class__",
+    "__annotations__", "__abstractmethods__", "__classcell__", 
"__parameters__",
+    "__type_params__", "__init_subclass__", "__subclasshook__", 
"__class_getitem__",
+    "__orig_bases__", "__getattribute__", "__setattr__", "__delattr__", 
"_abc_impl",
+})
+
+
+def _set_native(name, value):
+    if value is _missing:
+        if name in vars(_NativeDataFrame):
+            delattr(_NativeDataFrame, name)
+    else:
+        setattr(_NativeDataFrame, name, value)
+
+
+def _apply_native_state(name, value, attribute_lookup):
+    _set_native(name, value)
+    if name == "__getattr__":
+        # Apply generic lookup for a forwarded hook, or reinstall the saved 
PyO3
+        # wrapper to restore its original combined native lookup slot.
+        _set_native("__getattribute__", attribute_lookup)
+
+
+class _DataFrameMeta(ABCMeta):
+    def __init__(cls, name, bases, namespace, **kwargs):
+        super().__init__(name, bases, namespace, **kwargs)
+        if _public_dataframe is not None and type(cls) is _DataFrameMeta:
+            # A by-value cloudpickled user subclass must name a metaclass that
+            # official workers can import. Only the public base needs 
forwarding;
+            # ordinary subclasses retain standard ABC behavior. Preserve 
explicit
+            # user metaclass subclasses, which own their construction 
semantics.
+            type.__setattr__(cls, "__class__", ABCMeta)
+
+    def __setattr__(cls, name, value):
+        if cls is not _public_dataframe or name in _local_class_attributes:
+            return super().__setattr__(name, value)
+
+        # User extensions of the public base must be visible on native frames 
too.
+        # Restoring an initial public dispatcher must preserve any 
concrete-class
+        # patch that preceded the public override. Never install that 
dispatcher
+        # itself on the native type, which would make dynamic dispatch 
recursive.
+        initial = _initial_public_attributes.get(name, _missing)
+        native_before = vars(_NativeDataFrame).get(name, _missing)
+        lookup_before = vars(_NativeDataFrame).get("__getattribute__", 
_missing)
+        restoring = initial is not _missing and value is initial
+        override = _native_overrides.get(name)
+        still_forwarded = override is not None and native_before is 
override.forwarded
+        previous_native = override.previous_native if still_forwarded else 
native_before
+        previous_lookup = (
+            override.previous_lookup
+            if still_forwarded and lookup_before is object.__getattribute__
+            else lookup_before
+        )
+        if restoring:
+            native_value = previous_native
+            lookup_value = previous_lookup
+        else:
+            native_value = value
+            # PyO3's __getattribute__ wrapper already resolves missing names.
+            # A Python hook needs generic lookup first so it actually receives
+            # misses, rather than being bypassed by that native resolver.
+            lookup_value = object.__getattribute__
+        try:
+            _apply_native_state(name, native_value, lookup_value)
+            super().__setattr__(name, value)
+        except BaseException:
+            _apply_native_state(name, native_before, lookup_before)
+            raise
+        if restoring:
+            _native_overrides.pop(name, None)
+        else:
+            # A concrete change since the last forwarding becomes the new saved
+            # state, for initial members and newly added helpers alike.
+            _native_overrides[name] = _NativeOverride(
+                previous_native=previous_native,
+                forwarded=native_value,
+                previous_lookup=previous_lookup,
+            )
+
+    def __delattr__(cls, name):
+        if (
+            cls is not _public_dataframe
+            or name in _local_class_attributes
+            or name not in vars(cls)
+        ):
+            return super().__delattr__(name)
+
+        native_before = vars(_NativeDataFrame).get(name, _missing)
+        lookup_before = vars(_NativeDataFrame).get("__getattribute__", 
_missing)
+        # Deleting an initial public method removes only the base's exposure. 
Keep
+        # an independent concrete patch, or restore the pre-public-override 
method.
+        override = _native_overrides.get(name)
+        still_forwarded = override is not None and native_before is 
override.forwarded
+        native_value = override.previous_native if still_forwarded else 
native_before
+        lookup_value = (
+            override.previous_lookup
+            if still_forwarded and lookup_before is object.__getattribute__
+            else lookup_before
+        )
+        try:
+            _apply_native_state(name, native_value, lookup_value)
+            super().__delattr__(name)
+        except BaseException:
+            _apply_native_state(name, native_before, lookup_before)
+            raise
+        _native_overrides.pop(name, None)
+
+
+def _concrete_attribute(name, original):
+    # The concrete type's own implementation of a public-base attribute. A 
public-base
+    # override is forwarded to the concrete type, so that native frames see 
it; a wrapper
+    # often captures the public attribute and calls it from the override
+    # (orig = DataFrame.show; DataFrame.show = lambda self, *a: orig(self, 
*a)). The
+    # captured attribute then reaches the implementation that the override 
replaced, as
+    # in PySpark, where a public-base patch never reaches the concrete type. 
Resolving to
+    # the forwarded override itself would call the wrapper back without end.
+    current = vars(_NativeDataFrame).get(name, _missing)
+    override = _native_overrides.get(name)
+    if override is not None and current is override.forwarded:
+        current = override.previous_native
+    if current is _missing:
+        return original
+    get = getattr(type(current), "__get__", None)
+    return current if get is None else get(current, None, _NativeDataFrame)
+
+
+def _not_implemented(name):
+    from pyspark.errors import PySparkNotImplementedError
+
+    # PySpark dispatches public-base methods to the concrete implementation. An
+    # independent Python subclass supplies the operations for its own data 
model.
+    return PySparkNotImplementedError(
+        errorClass="NOT_IMPLEMENTED",
+        messageParameters={"feature": f"DataFrame.{name}"},
+    )
+
+
+def _dispatch_method(name, method):
+    @wraps(method)
+    def dispatched(self, *args, **kwargs):
+        if not isinstance(self, _NativeDataFrame):
+            if name == "__arrow_c_stream__":
+                from pyspark.sql.interchange import SparkArrowCStreamer
+
+                arguments = signature(method).bind(self, *args, **kwargs)
+                return SparkArrowCStreamer(self).__arrow_c_stream__(
+                    arguments.arguments.get("requested_schema")
+                )
+            if name in _empty_public_methods:
+                # Empty official bodies still enforce their Python signatures.
+                # Native calls keep their current implementation and argument 
handling.
+                signature(method).bind(self, *args, **kwargs)
+                return None
+            raise _not_implemented(name)
+        implementation = _concrete_attribute(name, method)
+        if implementation is dispatched:
+            implementation = method
+        return implementation(self, *args, **kwargs)
+
+    dispatched.__module__ = __name__
+    dispatched.__qualname__ = f"DataFrame.{name}"
+    return dispatched
+
+
+def _dispatch_property(name, descriptor):
+    def get(self):
+        if not isinstance(self, _NativeDataFrame):
+            # Official public-base properties have empty bodies. Independent
+            # Python subclasses therefore read None unless they override them.
+            return None
+        implementation = _concrete_attribute(name, descriptor)
+        if implementation is public_property:
+            implementation = descriptor
+        getter = getattr(implementation, "__get__", None)
+        return getter(self, type(self)) if getter is not None else 
implementation
+
+    get.__name__ = name
+    get.__module__ = __name__
+    get.__qualname__ = f"DataFrame.{name}"
+    public_property = property(get, doc=descriptor.__doc__)
+    return public_property
+
+
+class DataFrame(metaclass=_DataFrameMeta):
+    __doc__ = _NativeDataFrame.__doc__
+    is_cached: bool
+
+    def __new__(cls, plan, session):
+        # Retain this client's Connect constructor, including its keyword 
arguments.
+        # A Python subclass can override __new__ to use object.__new__(cls), 
as the
+        # reference client's MockDataset does, without allocating any Rust 
storage.
+        # As in the reference public factory, inheriting this __new__ still 
returns
+        # a concrete frame, rather than allocating an instance of the subclass.
+        return _NativeDataFrame(plan, session)
+
+    def __getattr__(self, name: str) -> Column:
+        if not isinstance(self, _NativeDataFrame):
+            raise _not_implemented("__getattr__")
+        # An explicit __getattr__ call resolves a column even when a regular
+        # attribute has that name. PyO3's resolver has no class-dict entry 
until a
+        # user overrides it, so use its ordinary native bridge as the default.
+        implementation = _concrete_attribute(
+            "__getattr__", _NativeDataFrame._get_column_by_attribute
+        )
+        if implementation is _initial_public_attributes["__getattr__"]:
+            implementation = _NativeDataFrame._get_column_by_attribute
+        return implementation(self, name)
+
+
+_initial_public_attributes["__getattr__"] = vars(DataFrame)["__getattr__"]
+
+
+# Expose the concrete implementation's real API on the public base. Native 
instances
+# continue to call their native methods directly. Explicit public-base calls
+# (DataFrame.select(frame, ...)) and inherited calls on independent Python 
subclasses
+# go through these dispatchers. There is no per-result wrapper and no change 
to the
+# native object's layout or allocator.
+for _name, _attribute in vars(_NativeDataFrame).items():
+    if _name in _local_class_attributes or _name in {
+        "__reduce__", "__reduce_ex__", "__getstate__", "__hash__", 
"__sizeof__",
+    }:
+        continue
+    if _name in {"_session", "_plan", "is_cached"}:
+        # These getters access native storage. Independent Python subclasses 
can
+        # assign ordinary instance attributes instead of inheriting those 
descriptors.
+        continue
+    if _name in {"__getattr__", "_get_column_by_attribute"}:
+        # The explicit public hook above owns the special-method dispatch. Its
+        # private native bridge is an implementation detail of the concrete 
type.
+        continue
+    if isinstance(_attribute, staticmethod):
+        _public_attribute = _attribute
+    elif isinstance(_attribute, (classmethod, ClassMethodDescriptorType)):
+        # There is no native DataFrame classmethod today. Require an explicit
+        # binding decision and real API tests when one is introduced.
+        raise TypeError(
+            f"Native DataFrame classmethod requires an explicit public 
binding: {_name}"
+        )
+    elif isinstance(_attribute, GetSetDescriptorType):
+        _public_attribute = _dispatch_property(_name, _attribute)
+    elif isinstance(_attribute, (FunctionType, MethodDescriptorType, 
WrapperDescriptorType)):
+        _public_attribute = _dispatch_method(_name, _attribute)
+    elif hasattr(type(_attribute), "__get__"):
+        raise TypeError(f"Unsupported native DataFrame descriptor: {_name}")
+    else:
+        _public_attribute = _attribute
+    # Initial exposure must not forward a Python dispatcher onto the native 
type.
+    type.__setattr__(DataFrame, _name, _public_attribute)
+    _initial_public_attributes[_name] = _public_attribute
+
+# Virtual inheritance preserves isinstance/issubclass without changing the 
native
+# object's layout. Its actual MRO stays native, while Python subclasses have 
the
+# ordinary Python layout required by object.__new__.
+DataFrame.register(_NativeDataFrame)
+_public_dataframe = DataFrame
+
+del _name, _attribute, _public_attribute
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 699bdcb2..46165f8a 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -6982,16 +6982,24 @@ import inspect  # noqa: E402
 
 import pyspark  # noqa: E402
 from pyspark.sql import SparkSession as _SS, DataFrame as _DF, Column as _Col  
# noqa: E402
+from pyspark.sql.connect.dataframe import DataFrame as _ConnectDF  # noqa: E402
 
 
 def test_dropin_version_is_spark_version():
     assert pyspark.__version__ == "4.3.0"
 
 
[email protected]("cls,name", [(_SS, "version"), (_DF, "dtypes"), (_DF, 
"executionInfo")])
-def test_property_not_method(cls, name):
-    # PySpark accesses these without parentheses; the Rust getter is a 
getset_descriptor.
-    assert type(inspect.getattr_static(cls, name)).__name__ == 
"getset_descriptor"
[email protected]("cls,name,descriptor", [
+    (_SS, "version", "getset_descriptor"),
+    (_ConnectDF, "dtypes", "getset_descriptor"),
+    (_ConnectDF, "executionInfo", "getset_descriptor"),
+    (_DF, "dtypes", "property"),
+    (_DF, "executionInfo", "property"),
+])
+def test_property_not_method(cls, name, descriptor):
+    # PySpark accesses these without parentheses. Concrete Rust getters remain
+    # getset descriptors; the Python public base exposes ordinary properties.
+    assert type(inspect.getattr_static(cls, name)).__name__ == descriptor
 
 
 def test_show_has_no_required_args_and_defaults_n_to_20():
@@ -7139,15 +7147,16 @@ def 
test_pandas_udf_eval_type_inferred_from_type_hints(mock_connect):
 # class itself unpicklable: pickle serializes a class BY REFERENCE, writing
 # __module__ + __qualname__ and re-importing on load, so 
"builtins.IntegerType" fails
 # the lookup. Every #[pyclass] therefore carries an explicit `module = "..."`.
-# NB: DataFrame/Column report the *connect* module: upstream 
pyspark.sql.{dataframe,
-# column} hold the abstract parent, while the concrete class a Connect session 
hands
-# out is pyspark.sql.connect.*.
+# The public DataFrame base reports pyspark.sql.dataframe, as in PySpark. 
Native
+# DataFrame/Column classes report the connect modules, which contain the 
concrete
+# classes returned by Connect sessions.
 
 
 @pytest.mark.parametrize(
     "cls,expected",
     [
-        (_DF, "pyspark.sql.connect.dataframe"),
+        (_DF, "pyspark.sql.dataframe"),
+        (_ConnectDF, "pyspark.sql.connect.dataframe"),
         (_Col, "pyspark.sql.connect.column"),
         (_SS, "pyspark.sql.session"),
         (T.DataType, "pyspark.sql.types"),
@@ -13201,13 +13210,16 @@ def 
test_positional_indexing_invalid_index_types_do_not_analyze(positional_index
 
 def 
test_positional_indexing_columns_filter_and_sequences_select(positional_indexing_analyzed):
     from pyspark.sql import DataFrame
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
 
     # As PySpark: a Column filters the rows, and a list or tuple selects its 
columns,
     # without looking the schema up. The live tests check the rows.
     spark, service = positional_indexing_analyzed
     df = spark.range(10)
     for item in [df["id"] > 1, ["id"], ("id", "id"), [["id"]], []]:
-        assert type(df[item]) is DataFrame
+        selected = df[item]
+        assert type(selected) is ConnectDataFrame
+        assert isinstance(selected, DataFrame)
     assert service.calls == 0
 
 
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index a9d97e9e..657b4839 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -780,6 +780,789 @@ def test_ml_dataframes_of_plans_keep_their_plans(ml_mock):
     assert alive() is None
 
 
+def test_public_dataframe_base_factory_and_native_dispatch(ml_mock):
+    import inspect
+    import pickle
+
+    from pyspark import cloudpickle
+    from pyspark.sql import DataFrame
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
+    from pyspark.sql.connect.plan import LogicalPlan
+
+    spark, service = ml_mock
+
+    class SQLPlan(LogicalPlan):
+        def __init__(self):
+            super().__init__(None)
+
+        def plan(self, session):
+            relation = self._create_proto_relation()
+            relation.sql.query = "SELECT 1 AS a"
+            return relation
+
+    frame = DataFrame(plan=SQLPlan(), session=spark)
+    assert type(frame) is ConnectDataFrame
+    assert isinstance(frame, DataFrame)
+    assert issubclass(ConnectDataFrame, DataFrame)
+    assert DataFrame.__module__ == "pyspark.sql.dataframe"
+    assert ConnectDataFrame.__module__ == "pyspark.sql.connect.dataframe"
+    assert DataFrame.__doc__ == ConnectDataFrame.__doc__
+    assert inspect.signature(DataFrame) == inspect.signature(ConnectDataFrame)
+    assert inspect.signature(DataFrame.select) == 
inspect.signature(ConnectDataFrame.select)
+    assert DataFrame.select.__doc__ == ConnectDataFrame.select.__doc__
+    assert {
+        name for name in dir(ConnectDataFrame)
+        if not name.startswith("_") and name != "is_cached"
+    } <= set(dir(DataFrame))
+
+    # Public-base unbound methods and properties dispatch to the real native 
frame;
+    # ordinary frame calls keep the native implementation and result type.
+    projected = DataFrame.select(frame, "a")
+    assert type(projected) is ConnectDataFrame
+    assert isinstance(projected, DataFrame)
+    assert DataFrame.sparkSession.fget(frame) is spark
+    assert DataFrame.sparkSession.fget.__name__ == "sparkSession"
+    assert DataFrame.sparkSession.fget.__module__ == "pyspark.sql.dataframe"
+    assert DataFrame.sparkSession.fget.__qualname__ == "DataFrame.sparkSession"
+    assert repr(DataFrame.__getitem__(frame, "a")) == "Column<'a'>"
+    restored = cloudpickle.loads(cloudpickle.dumps(frame))
+    assert type(restored) is ConnectDataFrame
+    assert _relation(restored).sql.query == "SELECT 1 AS a"
+    assert pickle.loads(pickle.dumps(DataFrame)) is DataFrame
+    assert pickle.loads(pickle.dumps(ConnectDataFrame)) is ConnectDataFrame
+
+    init_calls = []
+
+    class InheritedFactoryFrame(DataFrame):
+        def __init__(self, plan, session):
+            init_calls.append(self)
+
+    # As PySpark's public factory: inherited __new__ returns a concrete frame, 
so
+    # Python does not run the independent subclass's initializer.
+    factory_frame = InheritedFactoryFrame(plan=SQLPlan(), session=spark)
+    assert type(factory_frame) is ConnectDataFrame
+    assert not isinstance(factory_frame, InheritedFactoryFrame)
+    assert init_calls == []
+
+    class NativeFrame(ConnectDataFrame):
+        def __init__(self, plan, session):
+            self.marker = "native-subclass-state"
+
+    native_subclass = NativeFrame(plan=SQLPlan(), session=spark)
+    assert type(native_subclass) is NativeFrame
+    assert isinstance(native_subclass, DataFrame)
+    assert native_subclass.marker == "native-subclass-state"
+    assert type(native_subclass.select("a")) is ConnectDataFrame
+    assert service.execute_requests == []
+
+
+def test_public_dataframe_extensions_reach_native_frames_and_restore(ml_mock, 
monkeypatch):
+    import inspect
+
+    from pyspark.sql import DataFrame
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
+
+    spark, service = ml_mock
+    frame = spark.range(1)
+    original_public_count = vars(DataFrame)["count"]
+    original_native_count = vars(ConnectDataFrame)["count"]
+    original_public_schema = vars(DataFrame)["schema"]
+    original_native_schema = vars(ConnectDataFrame)["schema"]
+    original_native_session = vars(ConnectDataFrame)["_session"]
+    missing = object()
+
+    class LocalFrame(DataFrame):
+        def __new__(cls):
+            return object.__new__(cls)
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "compatibility_helper", lambda self: 42, 
raising=False)
+        assert frame.compatibility_helper() == 42
+        assert LocalFrame().compatibility_helper() == 42
+        with monkeypatch.context() as local_patch:
+            local_patch.setattr(LocalFrame, "compatibility_helper", lambda 
self: 7)
+            assert LocalFrame().compatibility_helper() == 7
+            assert frame.compatibility_helper() == 42
+        assert LocalFrame().compatibility_helper() == 42
+    assert "compatibility_helper" not in vars(DataFrame)
+    assert "compatibility_helper" not in vars(ConnectDataFrame)
+    assert inspect.getattr_static(frame, "compatibility_helper", missing) is 
missing
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "count", lambda self: 99)
+        assert frame.count() == 99
+        assert DataFrame.count(frame) == 99
+    assert vars(DataFrame)["count"] is original_public_count
+    assert vars(ConnectDataFrame)["count"] is original_native_count
+
+    with monkeypatch.context() as patch:
+        patch.delattr(DataFrame, "count")
+        assert "count" not in vars(DataFrame)
+        assert vars(ConnectDataFrame)["count"] is original_native_count
+        assert frame.count.__self__ is frame
+        assert frame.count.__name__ == "count"
+    assert vars(DataFrame)["count"] is original_public_count
+    assert vars(ConnectDataFrame)["count"] is original_native_count
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "count", lambda self: 99)
+        assert frame.count() == 99
+        del DataFrame.count
+        assert "count" not in vars(DataFrame)
+        assert vars(ConnectDataFrame)["count"] is original_native_count
+        assert frame.count.__self__ is frame
+    assert vars(DataFrame)["count"] is original_public_count
+    assert vars(ConnectDataFrame)["count"] is original_native_count
+
+    native_attributes = dict(vars(ConnectDataFrame))
+    with monkeypatch.context() as patch:
+        patch.setattr(
+            DataFrame,
+            "__subclasshook__",
+            classmethod(lambda cls, subclass: NotImplemented),
+        )
+        assert dict(vars(ConnectDataFrame)) == native_attributes
+    assert dict(vars(ConnectDataFrame)) == native_attributes
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "schema", property(lambda self: 
"custom-schema"))
+        assert frame.schema == "custom-schema"
+        assert LocalFrame().schema == "custom-schema"
+    assert vars(DataFrame)["schema"] is original_public_schema
+    assert vars(ConnectDataFrame)["schema"] is original_native_schema
+
+    # Explicit public calls must follow concrete-class patches at call time.
+    # Undoing or deleting a public override must preserve a concrete patch that
+    # was already in place, rather than reinstating an import-time descriptor.
+    with monkeypatch.context() as concrete_patch:
+        concrete_count = lambda self: 73
+        concrete_schema = property(lambda self: "concrete-schema")
+        concrete_patch.setattr(ConnectDataFrame, "count", concrete_count)
+        concrete_patch.setattr(ConnectDataFrame, "schema", concrete_schema)
+        assert DataFrame.count(frame) == frame.count() == 73
+        assert DataFrame.schema.fget(frame) == frame.schema == 
"concrete-schema"
+        with monkeypatch.context() as public_patch:
+            public_patch.setattr(DataFrame, "count", lambda self: 99)
+            public_patch.setattr(DataFrame, "schema", property(lambda self: 
"public-schema"))
+            assert DataFrame.count(frame) == frame.count() == 99
+            assert DataFrame.schema.fget(frame) == frame.schema == 
"public-schema"
+        assert vars(ConnectDataFrame)["count"] is concrete_count
+        assert vars(ConnectDataFrame)["schema"] is concrete_schema
+        assert DataFrame.count(frame) == 73
+        assert DataFrame.schema.fget(frame) == "concrete-schema"
+        with monkeypatch.context() as public_patch:
+            public_patch.delattr(DataFrame, "count")
+            public_patch.delattr(DataFrame, "schema")
+            assert frame.count() == 73
+            assert frame.schema == "concrete-schema"
+        assert DataFrame.count(frame) == 73
+        assert DataFrame.schema.fget(frame) == "concrete-schema"
+    assert vars(ConnectDataFrame)["count"] is original_native_count
+    assert vars(ConnectDataFrame)["schema"] is original_native_schema
+
+    try:
+        with monkeypatch.context() as public_patch:
+            public_patch.setattr(DataFrame, "count", lambda self: 99)
+            concrete_count = lambda self: 74
+            # A concrete patch installed after the public override also 
survives
+            # its undo. This assignment is owned by the surrounding finally.
+            setattr(ConnectDataFrame, "count", concrete_count)
+        assert vars(ConnectDataFrame)["count"] is concrete_count
+        assert DataFrame.count(frame) == frame.count() == 74
+    finally:
+        setattr(ConnectDataFrame, "count", original_native_count)
+    assert vars(DataFrame)["count"] is original_public_count
+
+    try:
+        with monkeypatch.context() as public_patch:
+            public_patch.setattr(DataFrame, "count", lambda self: 99)
+            concrete_count = lambda self: 75
+            setattr(ConnectDataFrame, "count", concrete_count)
+            public_patch.setattr(DataFrame, "count", lambda self: 100)
+            assert frame.count() == 100
+        assert vars(ConnectDataFrame)["count"] is concrete_count
+        assert DataFrame.count(frame) == frame.count() == 75
+    finally:
+        setattr(ConnectDataFrame, "count", original_native_count)
+    assert vars(DataFrame)["count"] is original_public_count
+
+    # Added helpers obey the same ownership rule as initial members, including
+    # deletion after a concrete patch and repeated public overrides.
+    for repeat_public_override in (False, True):
+        try:
+            with monkeypatch.context() as public_patch:
+                public_patch.setattr(
+                    DataFrame, "compatibility_helper", lambda self: 1, 
raising=False
+                )
+                concrete_helper = lambda self: 76
+                setattr(ConnectDataFrame, "compatibility_helper", 
concrete_helper)
+                if repeat_public_override:
+                    public_patch.setattr(DataFrame, "compatibility_helper", 
lambda self: 2)
+                    assert frame.compatibility_helper() == 2
+                public_patch.delattr(DataFrame, "compatibility_helper")
+                assert "compatibility_helper" not in vars(DataFrame)
+                assert vars(ConnectDataFrame)["compatibility_helper"] is 
concrete_helper
+                assert frame.compatibility_helper() == 76
+            assert "compatibility_helper" not in vars(DataFrame)
+            assert vars(ConnectDataFrame)["compatibility_helper"] is 
concrete_helper
+        finally:
+            if "compatibility_helper" in vars(ConnectDataFrame):
+                delattr(ConnectDataFrame, "compatibility_helper")
+
+    # A public extension may temporarily shadow a native-only descriptor. 
Removing
+    # that extension must recover the native getter rather than deleting it.
+    assert "_session" not in vars(DataFrame)
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "_session", property(lambda self: 
"custom-session"), raising=False)
+        assert frame._session == "custom-session"
+    assert "_session" not in vars(DataFrame)
+    assert vars(ConnectDataFrame)["_session"] is original_native_session
+    assert frame._session is spark
+
+    def set_custom_value(self, value):
+        self.custom_value = value
+
+    with monkeypatch.context() as patch:
+        patch.setattr(
+            DataFrame,
+            "compatibility_property",
+            property(lambda self: self.custom_value, set_custom_value),
+            raising=False,
+        )
+        frame.compatibility_property = 5
+        assert frame.compatibility_property == 5
+    assert "compatibility_property" not in vars(DataFrame)
+    assert "compatibility_property" not in vars(ConnectDataFrame)
+    assert service.execute_requests == []
+
+
+def test_public_dataframe_wrappers_call_the_concrete_attributes_they_captured(
+    ml_mock, monkeypatch
+):
+    # A wrapper of a public-base attribute often calls the attribute it 
captured before
+    # the patch. That reaches the implementation that the wrapper replaced, as 
on master
+    # and in PySpark, and not the wrapper again, which recursed without end.
+    from pyspark.sql import DataFrame
+
+    spark, service = ml_mock
+    frame = spark.range(3)
+    original_limit = vars(DataFrame)["limit"]
+    original_session = vars(DataFrame)["sparkSession"]
+    original_getattr = vars(DataFrame)["__getattr__"]
+    calls = []
+
+    def limit(self, num):
+        calls.append(("limit", num))
+        return original_limit(self, num)
+
+    def get_attribute(self, name):
+        calls.append(("__getattr__", name))
+        return original_getattr(self, name)
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "limit", limit)
+        patch.setattr(
+            DataFrame,
+            "sparkSession",
+            property(lambda self: ("wrapped", original_session.fget(self))),
+        )
+        patch.setattr(DataFrame, "__getattr__", get_attribute)
+        assert isinstance(frame.limit(1), DataFrame)
+        assert frame.sparkSession == ("wrapped", spark)
+        assert repr(frame.missing_column) == repr(frame["missing_column"])
+        # A wrapper of a wrapper reaches the concrete method through both.
+        inner = DataFrame.limit
+        patch.setattr(DataFrame, "limit", lambda self, num: ("outer", 
inner(self, num)))
+        outer, limited = frame.limit(2)
+        assert outer == "outer" and isinstance(limited, DataFrame)
+        assert calls == [("limit", 1), ("__getattr__", "missing_column"), 
("limit", 2)]
+    assert vars(DataFrame)["limit"] is original_limit
+    assert frame.sparkSession is spark
+    assert service.execute_requests == []
+
+
+def test_public_dataframe_attribute_dispatch_and_restore(ml_mock, monkeypatch):
+    import inspect
+
+    from pyspark.errors import PySparkAttributeError
+    from pyspark.sql import DataFrame
+    from pyspark.sql.column import Column
+    from pyspark.sql.connect.column import Column as ConnectColumn
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
+
+    spark, service = ml_mock
+    frame = spark.range(1)
+    monkeypatch.delenv("PYSPARK_VALIDATE_COLUMN_NAME_LEGACY", raising=False)
+    original_public_getattr = vars(DataFrame)["__getattr__"]
+    original_native_lookup = vars(ConnectDataFrame)["__getattribute__"]
+    original_native_attributes = dict(vars(ConnectDataFrame))
+    native_resolver = vars(ConnectDataFrame)["_get_column_by_attribute"]
+    getattr_signature = inspect.signature(DataFrame.__getattr__)
+    assert getattr_signature.parameters["name"].annotation is str
+    assert getattr_signature.return_annotation is Column
+    assert Column is ConnectColumn
+    assert "__getattr__" not in vars(ConnectDataFrame)
+    assert "__getattr__" in dir(DataFrame)
+    assert "_get_column_by_attribute" in dir(ConnectDataFrame)
+    assert "_get_column_by_attribute" not in vars(DataFrame)
+    assert repr(native_resolver(frame, "count")) == "Column<'count'>"
+    assert repr(DataFrame.__getattr__(frame, "a")) == "Column<'a'>"
+    # Explicit __getattr__ resolves a column even when a method has that name.
+    assert repr(DataFrame.__getattr__(frame, "count")) == "Column<'count'>"
+    for name, condition in (
+        ("rdd", "JVM_ATTRIBUTE_NOT_SUPPORTED"),
+        ("__missing_column__", "ATTRIBUTE_NOT_SUPPORTED"),
+    ):
+        with pytest.raises(PySparkAttributeError) as error:
+            DataFrame.__getattr__(frame, name)
+        assert error.value.getCondition() == condition
+        assert error.value.getMessageParameters() == {"attr_name": name}
+    with monkeypatch.context() as patch:
+        patch.setenv("PYSPARK_VALIDATE_COLUMN_NAME_LEGACY", "1")
+        with pytest.raises(PySparkAttributeError) as error:
+            DataFrame.__getattr__(frame, "missing_column")
+        assert error.value.getCondition() == "ATTRIBUTE_NOT_SUPPORTED"
+        assert error.value.getMessageParameters() == {"attr_name": 
"missing_column"}
+
+    delegated_calls = []
+
+    class NativeFrame(ConnectDataFrame):
+        def __getattr__(self, name):
+            delegated_calls.append(name)
+            return DataFrame.__getattr__(self, name)
+
+    native_subclass = NativeFrame(plan=frame._plan, session=spark)
+    assert repr(NativeFrame.__getattr__(native_subclass, "count")) == 
"Column<'count'>"
+    assert delegated_calls == ["count"]
+    forwarded_calls = []
+
+    def custom_getattr(self, name):
+        forwarded_calls.append((self, name))
+        return ("custom", name)
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "__getattr__", custom_getattr)
+        assert vars(ConnectDataFrame)["__getattribute__"] is 
object.__getattribute__
+        assert frame.missing_column == ("custom", "missing_column")
+        assert DataFrame.__getattr__(frame, "count") == ("custom", "count")
+        assert len(forwarded_calls) == 2
+        assert all(item[0] is frame for item in forwarded_calls)
+        assert [item[1] for item in forwarded_calls] == ["missing_column", 
"count"]
+        assert frame.count.__self__ is frame
+        patch.setattr(DataFrame, "__getattr__", lambda self, name: ("second", 
name))
+        assert frame.missing_column == ("second", "missing_column")
+    assert vars(DataFrame)["__getattr__"] is original_public_getattr
+    assert "__getattr__" not in vars(ConnectDataFrame)
+    assert vars(ConnectDataFrame)["__getattribute__"] is original_native_lookup
+    assert dict(vars(ConnectDataFrame)) == original_native_attributes
+    assert repr(frame.a) == "Column<'a'>"
+    assert frame.count.__self__ is frame
+    assert repr(DataFrame.__getattr__(frame, "count")) == "Column<'count'>"
+    with pytest.raises(PySparkAttributeError) as error:
+        frame.__missing_column__
+    assert error.value.getCondition() == "ATTRIBUTE_NOT_SUPPORTED"
+    assert error.value.getMessageParameters() == {"attr_name": 
"__missing_column__"}
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "__getattr__", custom_getattr)
+        patch.delattr(DataFrame, "__getattr__")
+        assert "__getattr__" not in vars(ConnectDataFrame)
+        assert vars(ConnectDataFrame)["__getattribute__"] is 
original_native_lookup
+        assert repr(frame.a) == "Column<'a'>"
+        assert frame.count.__self__ is frame
+    assert vars(DataFrame)["__getattr__"] is original_public_getattr
+    assert "__getattr__" not in vars(ConnectDataFrame)
+    assert vars(ConnectDataFrame)["__getattribute__"] is original_native_lookup
+    assert dict(vars(ConnectDataFrame)) == original_native_attributes
+    assert repr(frame.a) == "Column<'a'>"
+    assert service.execute_requests == []
+
+
[email protected]("lookup_first", [False, True])
[email protected]("undo_lookup_first", [False, True])
+def test_public_dataframe_lookup_protocol_is_local_during_hook_overrides(
+    ml_mock, monkeypatch, lookup_first, undo_lookup_first
+):
+    from pyspark.errors import PySparkNotImplementedError
+    from pyspark.sql import DataFrame
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
+
+    spark, service = ml_mock
+    frame = spark.range(1)
+    monkeypatch.delenv("PYSPARK_VALIDATE_COLUMN_NAME_LEGACY", raising=False)
+    original_native_attributes = dict(vars(ConnectDataFrame))
+    original_public_attributes = dict(vars(DataFrame))
+    original_native_lookup = vars(ConnectDataFrame)["__getattribute__"]
+    local_lookup_calls, hook_calls = [], []
+
+    class BeforeFrame(DataFrame):
+        def __new__(cls):
+            return object.__new__(cls)
+
+    before_frame = BeforeFrame()
+
+    def local_lookup(self, name):
+        if name == "local_marker":
+            local_lookup_calls.append(id(self))
+            return "local-value"
+        return object.__getattribute__(self, name)
+
+    def forwarded_hook(self, name):
+        hook_calls.append((id(self), name))
+        return ("forwarded", name)
+
+    with monkeypatch.context() as lookup_patch, monkeypatch.context() as 
hook_patch:
+        install_order = ("lookup", "hook") if lookup_first else ("hook", 
"lookup")
+        for protocol in install_order:
+            native_before = dict(vars(ConnectDataFrame))
+            if protocol == "lookup":
+                lookup_patch.setattr(DataFrame, "__getattribute__", 
local_lookup)
+                assert dict(vars(ConnectDataFrame)) == native_before
+            else:
+                hook_patch.setattr(DataFrame, "__getattr__", forwarded_hook)
+                assert vars(ConnectDataFrame)["__getattribute__"] is 
object.__getattribute__
+
+        class DuringFrame(BeforeFrame):
+            pass
+
+        during_frame = DuringFrame()
+        for independent in (before_frame, during_frame):
+            assert independent.local_marker == "local-value"
+            assert independent.missing_value == ("forwarded", "missing_value")
+        assert local_lookup_calls == [id(before_frame), id(during_frame)]
+        assert frame.local_marker == ("forwarded", "local_marker")
+        assert local_lookup_calls == [id(before_frame), id(during_frame)]
+        assert frame.missing_value == ("forwarded", "missing_value")
+        assert hook_calls[-1] == (id(frame), "missing_value")
+        assert frame.count.__self__ is frame
+
+        undo_order = ("lookup", "hook") if undo_lookup_first else ("hook", 
"lookup")
+        for protocol in undo_order:
+            native_before = dict(vars(ConnectDataFrame))
+            if protocol == "lookup":
+                lookup_patch.undo()
+                assert dict(vars(ConnectDataFrame)) == native_before
+            else:
+                hook_patch.undo()
+                assert dict(vars(ConnectDataFrame)) == 
original_native_attributes
+                assert vars(ConnectDataFrame)["__getattribute__"] is 
original_native_lookup
+                assert "__getattr__" not in vars(ConnectDataFrame)
+                assert repr(frame.a) == "Column<'a'>"
+                assert frame.count.__self__ is frame
+
+    assert dict(vars(DataFrame)) == original_public_attributes
+    assert dict(vars(ConnectDataFrame)) == original_native_attributes
+    assert repr(frame.a) == "Column<'a'>"
+    for independent in (before_frame, during_frame):
+        with pytest.raises(PySparkNotImplementedError) as error:
+            independent.local_marker
+        assert error.value.getCondition() == "NOT_IMPLEMENTED"
+        assert error.value.getMessageParameters() == {"feature": 
"DataFrame.__getattr__"}
+    assert service.execute_requests == []
+
+
+def 
test_public_dataframe_state_protocols_apply_only_to_python_subclasses(ml_mock, 
monkeypatch):
+    from pyspark.sql import DataFrame
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
+
+    spark, service = ml_mock
+    frame = spark.range(1)
+    original_native_attributes = dict(vars(ConnectDataFrame))
+    original_public_attributes = dict(vars(DataFrame))
+    set_calls, delete_calls = [], []
+
+    class BeforeFrame(DataFrame):
+        def __new__(cls):
+            return object.__new__(cls)
+
+    before_frame = BeforeFrame()
+
+    def local_setattr(self, name, value):
+        set_calls.append((id(self), name, value))
+        object.__setattr__(self, name, value)
+
+    def local_delattr(self, name):
+        delete_calls.append((id(self), name))
+        object.__delattr__(self, name)
+
+    with monkeypatch.context() as patch:
+        patch.setattr(DataFrame, "__setattr__", local_setattr)
+        patch.setattr(DataFrame, "__delattr__", local_delattr)
+        assert dict(vars(ConnectDataFrame)) == original_native_attributes
+
+        class DuringFrame(BeforeFrame):
+            pass
+
+        during_frame = DuringFrame()
+        for independent in (before_frame, during_frame):
+            independent.value = 8
+            assert independent.value == 8
+            del independent.value
+            assert "value" not in vars(independent)
+        assert set_calls == [(id(before_frame), "value", 8), 
(id(during_frame), "value", 8)]
+        assert delete_calls == [(id(before_frame), "value"), 
(id(during_frame), "value")]
+        frame._protocol_state = 9
+        assert frame._protocol_state == 9
+        del frame._protocol_state
+        assert "_protocol_state" not in vars(frame)
+        assert set_calls == [(id(before_frame), "value", 8), 
(id(during_frame), "value", 8)]
+        assert delete_calls == [(id(before_frame), "value"), 
(id(during_frame), "value")]
+        assert dict(vars(ConnectDataFrame)) == original_native_attributes
+
+    assert dict(vars(DataFrame)) == original_public_attributes
+    assert dict(vars(ConnectDataFrame)) == original_native_attributes
+    before_frame.value = 10
+    del before_frame.value
+    assert len(set_calls) == len(delete_calls) == 2
+    assert service.execute_requests == []
+
+
+def test_python_dataframe_subclasses_can_own_their_state():
+    from pyspark.errors import PySparkNotImplementedError
+    from pyspark.sql import DataFrame
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
+
+    class MemoryFrame(DataFrame):
+        def __new__(cls, values):
+            return object.__new__(cls)
+
+        def __init__(self, values):
+            self.values = list(values)
+            self._session = "own-session"
+            self._plan = "own-plan"
+            self.is_cached = False
+
+        def collect(self):
+            return list(self.values)
+
+        def count(self):
+            return len(self.collect())
+
+    class CountedFrame(MemoryFrame):
+        def count(self):
+            return super().count() + 1
+
+    frame = CountedFrame([1, 2])
+    assert isinstance(frame, DataFrame)
+    assert not isinstance(frame, ConnectDataFrame)
+    assert issubclass(CountedFrame, DataFrame)
+    assert frame.collect() == [1, 2]
+    assert frame.count() == 3
+    assert vars(frame) == {
+        "values": [1, 2], "_session": "own-session", "_plan": "own-plan", 
"is_cached": False
+    }
+    assert frame._session == "own-session" and frame._plan == "own-plan"
+    assert frame.is_cached is False
+    frame.is_cached = True
+    assert frame.is_cached is True
+    assert DataFrame.__annotations__["is_cached"] is bool
+    assert "is_cached" not in vars(DataFrame)
+    # Official public properties have empty bodies; independent subclasses can
+    # override them, and otherwise read None without disrupting hasattr.
+    assert frame.sparkSession is None
+    assert frame.schema is None
+    assert DataFrame.columns.fget(frame) is None
+    assert hasattr(frame, "schema")
+    # Public-base methods, including repr and dir, use PySpark's dispatch 
contract:
+    # native operations cannot operate on an independent Python data model.
+    for operation, name in (
+        (lambda: DataFrame.count(frame), "count"),
+        (lambda: repr(frame), "__repr__"),
+        (lambda: dir(frame), "__dir__"),
+        (lambda: frame.missing_attribute, "__getattr__"),
+        (lambda: hasattr(frame, "missing_attribute"), "__getattr__"),
+    ):
+        with pytest.raises(PySparkNotImplementedError) as error:
+            operation()
+        assert error.value.getCondition() == "NOT_IMPLEMENTED"
+        assert error.value.getMessageParameters() == {"feature": 
f"DataFrame.{name}"}
+
+
[email protected]("name,args,kwargs", [
+    ("checkpoint", (False,), {}),
+    ("localCheckpoint", (), {"eager": False, "storageLevel": "own-storage"}),
+    ("lateralJoin", ("other",), {"on": "condition", "how": "join-type"}),
+    (
+        "nearestByJoin", ("other", "ranking", 3, "exact", "distance"),
+        {"joinType": "left"},
+    ),
+    ("toPandas", (), {}),
+    ("asTable", (), {}),
+    ("scalar", (), {}),
+    ("exists", (), {}),
+])
+def test_python_dataframe_undecorated_methods_keep_official_fallbacks(name, 
args, kwargs):
+    from pyspark.sql import DataFrame
+
+    class MemoryFrame(DataFrame):
+        def __new__(cls):
+            return object.__new__(cls)
+
+    frame = MemoryFrame()
+    method = getattr(frame, name)
+    assert method(*args, **kwargs) is None
+    assert getattr(DataFrame, name)(frame, *args, **kwargs) is None
+    if name in {"checkpoint", "localCheckpoint"}:
+        assert method() is None
+    # Official empty methods enforce arity before returning None, without
+    # validating or converting the supplied values.
+    with pytest.raises(TypeError):
+        method(*args, **kwargs, unexpected=True)
+    with pytest.raises(TypeError):
+        method(*args, *([None] * 8), **kwargs)
+    if name in {"lateralJoin", "nearestByJoin"}:
+        with pytest.raises(TypeError):
+            method()
+    if name == "nearestByJoin":
+        with pytest.raises(TypeError):
+            method(*args, "left")
+
+
+def test_python_dataframe_arrow_stream_uses_generic_helper(monkeypatch):
+    from pyspark.sql import DataFrame, interchange
+
+    class MemoryFrame(DataFrame):
+        def __new__(cls):
+            return object.__new__(cls)
+
+    frame = MemoryFrame()
+    requested_schema = object()
+    stream = object()
+    calls = []
+
+    class Streamer:
+        def __init__(self, dataframe):
+            assert dataframe is frame
+
+        def __arrow_c_stream__(self, schema):
+            calls.append(schema)
+            return stream
+
+    monkeypatch.setattr(interchange, "SparkArrowCStreamer", Streamer)
+    assert frame.__arrow_c_stream__() is stream
+    assert frame.__arrow_c_stream__(requested_schema) is stream
+    assert DataFrame.__arrow_c_stream__(frame, 
requested_schema=requested_schema) is stream
+    assert calls == [None, requested_schema, requested_schema]
+    with pytest.raises(TypeError):
+        frame.__arrow_c_stream__(requested_schema, requested_schema)
+    with pytest.raises(TypeError):
+        frame.__arrow_c_stream__(unexpected=True)
+    with pytest.raises(TypeError):
+        frame.__arrow_c_stream__(requested_schema, 
requested_schema=requested_schema)
+    assert calls == [None, requested_schema, requested_schema]
+
+
+def test_public_dataframe_fallback_methods_still_dispatch_to_native(ml_mock, 
monkeypatch):
+    from pyspark.sql import DataFrame
+    from pyspark.sql.connect.dataframe import DataFrame as ConnectDataFrame
+
+    spark, service = ml_mock
+    frame = spark.range(1)
+    marker = object()
+    result = object()
+    calls = []
+
+    def implementation(self, value, *, option):
+        calls.append((self, value, option))
+        return result
+
+    for name in (
+        "checkpoint", "localCheckpoint", "lateralJoin", "nearestByJoin", 
"toPandas",
+        "asTable", "scalar", "exists", "__arrow_c_stream__",
+    ):
+        with monkeypatch.context() as patch:
+            patch.setattr(ConnectDataFrame, name, implementation)
+            # A native receiver uses the current concrete implementation's
+            # signature, even when the independent fallback has another arity.
+            assert getattr(DataFrame, name)(frame, marker, option=marker) is 
result
+            assert calls[-1] == (frame, marker, marker)
+    assert len(calls) == 9
+    assert service.execute_requests == []
+
+
+def test_local_dataframe_subclasses_cloudpickle_with_importable_metaclass():
+    from abc import ABCMeta
+
+    from pyspark import cloudpickle
+    from pyspark.sql import DataFrame
+
+    class MemoryFrame(DataFrame):
+        def __new__(cls, values):
+            return object.__new__(cls)
+
+        def __init__(self, values):
+            self.values = list(values)
+
+        def count(self):
+            return len(self.values)
+
+    class CountedFrame(MemoryFrame):
+        def count(self):
+            return super().count() + 1
+
+    def count_values(values):
+        return CountedFrame(values).count()
+
+    assert type(MemoryFrame) is ABCMeta
+    assert type(CountedFrame) is ABCMeta
+    payload = cloudpickle.dumps((CountedFrame, count_values))
+    assert b"_DataFrameMeta" not in payload
+    restored_class, restored_function = cloudpickle.loads(payload)
+    assert issubclass(restored_class, DataFrame)
+    assert restored_class([1, 2]).count() == 3
+    assert restored_function([1, 2, 3]) == 4
+
+    class UserMeta(type(DataFrame)):
+        pass
+
+    class UserFrame(DataFrame, metaclass=UserMeta):
+        def __new__(cls):
+            return object.__new__(cls)
+
+    assert type(UserFrame) is UserMeta
+    assert isinstance(UserFrame(), DataFrame)
+
+
+def test_python_dataframe_subclass_with_official_mock_pipeline():
+    # This is the no-server behavior of official 
PipelineTestsMixin.test_pipeline,
+    # using its actual vendored MockDataset, estimators and transformers.
+    from pyspark.errors import PySparkNotImplementedError
+    from pyspark.ml import Pipeline
+    from pyspark.sql import DataFrame
+    from pyspark.testing.mlutils import MockDataset, MockEstimator, 
MockTransformer
+
+    dataset = MockDataset()
+    assert isinstance(dataset, DataFrame)
+    with pytest.raises(PySparkNotImplementedError) as error:
+        hasattr(dataset, "missing_attribute")
+    assert error.value.getCondition() == "NOT_IMPLEMENTED"
+    assert error.value.getMessageParameters() == {"feature": 
"DataFrame.__getattr__"}
+    estimator0, transformer1 = MockEstimator(), MockTransformer()
+    estimator2, transformer3 = MockEstimator(), MockTransformer()
+    model = Pipeline(stages=[estimator0, transformer1, estimator2, 
transformer3]).fit(
+        dataset, {estimator0.fake: 0, transformer1.fake: 1}
+    )
+    model0, transformer1, model2, transformer3 = model.stages
+    assert model0.dataset_index == 0 and model0.getFake() == 0
+    assert transformer1.dataset_index == 1 and transformer1.getFake() == 1
+    assert dataset.index == 2
+    assert model2.dataset_index is None and transformer3.dataset_index is None
+    assert model.transform(dataset) is dataset
+    assert [stage.dataset_index for stage in model.stages] == [2, 3, 4, 5]
+    assert dataset.index == 6
+
+
+def test_python_dataframe_subclass_with_official_identity_pipeline():
+    from pyspark.ml import Pipeline
+    from pyspark.testing.mlutils import MockDataset
+
+    dataset = MockDataset()
+    assert Pipeline(stages=[]).fit(dataset).transform(dataset) is dataset
+    assert dataset.index == 0
+    with pytest.raises(KeyError):
+        Pipeline().fit(dataset)
+
+
 def test_ml_logical_plan_ids_as_pyspark():
     # As PySpark Connect's LogicalPlan: a plan ID of each plan, and another of 
a plan with
     # references, which _plan_id is.


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

Reply via email to