Skip to content

Commit 05ec47e

Browse files
committed
UNPICK
1 parent 68139c8 commit 05ec47e

File tree

11 files changed

+56
-451
lines changed

11 files changed

+56
-451
lines changed

docs/source/user-guide/dataframe/index.rst

Lines changed: 1 addition & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -145,39 +145,10 @@ To materialize the results of your DataFrame operations:
145145
146146
# Display results
147147
df.show() # Print tabular format to console
148-
148+
149149
# Count rows
150150
count = df.count()
151151
152-
PyArrow Streaming
153-
-----------------
154-
155-
DataFusion DataFrames implement the ``__arrow_c_stream__`` protocol, enabling
156-
zero-copy streaming into libraries like `PyArrow <https://arrow.apache.org/>`_.
157-
Earlier versions eagerly converted the entire DataFrame when exporting to
158-
PyArrow, which could exhaust memory on large datasets. With streaming, batches
159-
are produced lazily so you can process arbitrarily large results without
160-
out-of-memory errors.
161-
162-
.. code-block:: python
163-
164-
import pyarrow as pa
165-
166-
# Create a PyArrow RecordBatchReader without materializing all batches
167-
reader = pa.RecordBatchReader._import_from_c_capsule(df.__arrow_c_stream__())
168-
for batch in reader:
169-
... # process each batch as it is produced
170-
171-
DataFrames are also iterable, yielding :class:`pyarrow.RecordBatch` objects
172-
lazily so you can loop over results directly:
173-
174-
.. code-block:: python
175-
176-
for batch in df:
177-
... # process each batch as it is produced
178-
179-
See :doc:`../io/arrow` for additional details on the Arrow interface.
180-
181152
HTML Rendering
182153
--------------
183154

python/datafusion/_testing.py

Lines changed: 0 additions & 46 deletions
This file was deleted.

python/datafusion/context.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -731,7 +731,6 @@ def from_polars(self, data: pl.DataFrame, name: str | None = None) -> DataFrame:
731731
"""
732732
return DataFrame(self.ctx.from_polars(data, name))
733733

734-
735734
# https://github.com/apache/datafusion-python/pull/1016#discussion_r1983239116
736735
# is the discussion on how we arrived at adding register_view
737736
def register_view(self, name: str, df: DataFrame) -> None:

python/datafusion/dataframe.py

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
TYPE_CHECKING,
2727
Any,
2828
Iterable,
29-
Iterator,
3029
Literal,
3130
Optional,
3231
Union,
@@ -290,9 +289,6 @@ def __init__(
290289
class DataFrame:
291290
"""Two dimensional table representation of data.
292291
293-
DataFrame objects are iterable; iterating over a DataFrame yields
294-
:class:`pyarrow.RecordBatch` instances lazily.
295-
296292
See :ref:`user_guide_concepts` in the online documentation for more information.
297293
"""
298294

@@ -1102,37 +1098,21 @@ def unnest_columns(self, *columns: str, preserve_nulls: bool = True) -> DataFram
11021098
return DataFrame(self.df.unnest_columns(columns, preserve_nulls=preserve_nulls))
11031099

11041100
def __arrow_c_stream__(self, requested_schema: object | None = None) -> object:
1105-
"""Export the DataFrame as an Arrow C Stream.
1101+
"""Export an Arrow PyCapsule Stream.
11061102
1107-
The DataFrame is executed using DataFusion's streaming APIs and exposed via
1108-
Arrow's C Stream interface. Record batches are produced incrementally, so the
1109-
full result set is never materialized in memory. When ``requested_schema`` is
1110-
provided, only straightforward projections such as column selection or
1111-
reordering are applied.
1103+
This will execute and collect the DataFrame. We will attempt to respect the
1104+
requested schema, but only trivial transformations will be applied such as only
1105+
returning the fields listed in the requested schema if their data types match
1106+
those in the DataFrame.
11121107
11131108
Args:
11141109
requested_schema: Attempt to provide the DataFrame using this schema.
11151110
11161111
Returns:
1117-
Arrow PyCapsule object representing an ``ArrowArrayStream``.
1112+
Arrow PyCapsule object.
11181113
"""
1119-
# ``DataFrame.__arrow_c_stream__`` in the Rust extension leverages
1120-
# ``execute_stream`` under the hood to stream batches one at a time.
11211114
return self.df.__arrow_c_stream__(requested_schema)
11221115

1123-
def __iter__(self) -> Iterator[pa.RecordBatch]:
1124-
"""Yield record batches from the DataFrame without materializing results.
1125-
1126-
This implementation streams record batches via the Arrow C Stream
1127-
interface, allowing callers such as :func:`pyarrow.Table.from_batches` to
1128-
consume results lazily. The DataFrame is executed using DataFusion's
1129-
streaming APIs so ``collect`` is never invoked.
1130-
"""
1131-
import pyarrow as pa
1132-
1133-
reader = pa.RecordBatchReader._import_from_c_capsule(self.__arrow_c_stream__())
1134-
yield from reader
1135-
11361116
def transform(self, func: Callable[..., DataFrame], *args: Any) -> DataFrame:
11371117
"""Apply a function to the current DataFrame which returns another DataFrame.
11381118

python/tests/conftest.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import pyarrow as pa
1919
import pytest
20-
from datafusion import DataFrame, SessionContext
20+
from datafusion import SessionContext
2121
from pyarrow.csv import write_csv
2222

2323

@@ -49,12 +49,3 @@ def database(ctx, tmp_path):
4949
delimiter=",",
5050
schema_infer_max_records=10,
5151
)
52-
53-
54-
@pytest.fixture
55-
def fail_collect(monkeypatch):
56-
def _fail_collect(self, *args, **kwargs): # pragma: no cover - failure path
57-
msg = "collect should not be called"
58-
raise AssertionError(msg)
59-
60-
monkeypatch.setattr(DataFrame, "collect", _fail_collect)

python/tests/test_dataframe.py

Lines changed: 0 additions & 128 deletions
Original file line numberDiff line numberDiff line change
@@ -1582,30 +1582,6 @@ def test_empty_to_arrow_table(df):
15821582
assert set(pyarrow_table.column_names) == {"a", "b", "c"}
15831583

15841584

1585-
def test_arrow_c_stream_to_table(fail_collect):
1586-
ctx = SessionContext()
1587-
1588-
# Create a DataFrame with two separate record batches
1589-
batch1 = pa.record_batch([pa.array([1])], names=["a"])
1590-
batch2 = pa.record_batch([pa.array([2])], names=["a"])
1591-
df = ctx.create_dataframe([[batch1], [batch2]])
1592-
1593-
table = pa.Table.from_batches(df)
1594-
expected = pa.Table.from_batches([batch1, batch2])
1595-
1596-
assert table.equals(expected)
1597-
assert table.schema == df.schema()
1598-
assert table.column("a").num_chunks == 2
1599-
1600-
1601-
def test_arrow_c_stream_reader(df):
1602-
reader = pa.RecordBatchReader._import_from_c_capsule(df.__arrow_c_stream__())
1603-
assert isinstance(reader, pa.RecordBatchReader)
1604-
table = pa.Table.from_batches(reader)
1605-
expected = pa.Table.from_batches(df.collect())
1606-
assert table.equals(expected)
1607-
1608-
16091585
def test_to_pylist(df):
16101586
# Convert datafusion dataframe to Python list
16111587
pylist = df.to_pylist()
@@ -2690,110 +2666,6 @@ def trigger_interrupt():
26902666
interrupt_thread.join(timeout=1.0)
26912667

26922668

2693-
def test_arrow_c_stream_interrupted():
2694-
"""__arrow_c_stream__ responds to ``KeyboardInterrupt`` signals.
2695-
2696-
Similar to ``test_collect_interrupted`` this test issues a long running
2697-
query, but consumes the results via ``__arrow_c_stream__``. It then raises
2698-
``KeyboardInterrupt`` in the main thread and verifies that the stream
2699-
iteration stops promptly with the appropriate exception.
2700-
"""
2701-
2702-
ctx = SessionContext()
2703-
2704-
batches = []
2705-
for i in range(10):
2706-
batch = pa.RecordBatch.from_arrays(
2707-
[
2708-
pa.array(list(range(i * 1000, (i + 1) * 1000))),
2709-
pa.array([f"value_{j}" for j in range(i * 1000, (i + 1) * 1000)]),
2710-
],
2711-
names=["a", "b"],
2712-
)
2713-
batches.append(batch)
2714-
2715-
ctx.register_record_batches("t1", [batches])
2716-
ctx.register_record_batches("t2", [batches])
2717-
2718-
df = ctx.sql(
2719-
"""
2720-
WITH t1_expanded AS (
2721-
SELECT
2722-
a,
2723-
b,
2724-
CAST(a AS DOUBLE) / 1.5 AS c,
2725-
CAST(a AS DOUBLE) * CAST(a AS DOUBLE) AS d
2726-
FROM t1
2727-
CROSS JOIN (SELECT 1 AS dummy FROM t1 LIMIT 5)
2728-
),
2729-
t2_expanded AS (
2730-
SELECT
2731-
a,
2732-
b,
2733-
CAST(a AS DOUBLE) * 2.5 AS e,
2734-
CAST(a AS DOUBLE) * CAST(a AS DOUBLE) * CAST(a AS DOUBLE) AS f
2735-
FROM t2
2736-
CROSS JOIN (SELECT 1 AS dummy FROM t2 LIMIT 5)
2737-
)
2738-
SELECT
2739-
t1.a, t1.b, t1.c, t1.d,
2740-
t2.a AS a2, t2.b AS b2, t2.e, t2.f
2741-
FROM t1_expanded t1
2742-
JOIN t2_expanded t2 ON t1.a % 100 = t2.a % 100
2743-
WHERE t1.a > 100 AND t2.a > 100
2744-
"""
2745-
)
2746-
2747-
reader = pa.RecordBatchReader._import_from_c_capsule(df.__arrow_c_stream__())
2748-
2749-
interrupted = False
2750-
interrupt_error = None
2751-
query_started = threading.Event()
2752-
max_wait_time = 5.0
2753-
2754-
def trigger_interrupt():
2755-
start_time = time.time()
2756-
while not query_started.is_set():
2757-
time.sleep(0.1)
2758-
if time.time() - start_time > max_wait_time:
2759-
msg = f"Query did not start within {max_wait_time} seconds"
2760-
raise RuntimeError(msg)
2761-
2762-
thread_id = threading.main_thread().ident
2763-
if thread_id is None:
2764-
msg = "Cannot get main thread ID"
2765-
raise RuntimeError(msg)
2766-
2767-
exception = ctypes.py_object(KeyboardInterrupt)
2768-
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
2769-
ctypes.c_long(thread_id), exception
2770-
)
2771-
if res != 1:
2772-
ctypes.pythonapi.PyThreadState_SetAsyncExc(
2773-
ctypes.c_long(thread_id), ctypes.py_object(0)
2774-
)
2775-
msg = "Failed to raise KeyboardInterrupt in main thread"
2776-
raise RuntimeError(msg)
2777-
2778-
interrupt_thread = threading.Thread(target=trigger_interrupt)
2779-
interrupt_thread.daemon = True
2780-
interrupt_thread.start()
2781-
2782-
try:
2783-
query_started.set()
2784-
# consume the reader which should block and be interrupted
2785-
reader.read_all()
2786-
except KeyboardInterrupt:
2787-
interrupted = True
2788-
except Exception as e: # pragma: no cover - unexpected errors
2789-
interrupt_error = e
2790-
2791-
if not interrupted:
2792-
pytest.fail(f"Stream was not interrupted; got error: {interrupt_error}")
2793-
2794-
interrupt_thread.join(timeout=1.0)
2795-
2796-
27972669
def test_show_select_where_no_rows(capsys) -> None:
27982670
ctx = SessionContext()
27992671
df = ctx.sql("SELECT 1 WHERE 1=0")

python/tests/test_io.py

Lines changed: 0 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@
1717
from pathlib import Path
1818

1919
import pyarrow as pa
20-
import pytest
2120
from datafusion import column
22-
from datafusion._testing import range_table
2321
from datafusion.io import read_avro, read_csv, read_json, read_parquet
2422

2523

@@ -94,38 +92,3 @@ def test_read_avro():
9492
path = Path.cwd() / "testing/data/avro/alltypes_plain.avro"
9593
avro_df = read_avro(path=path)
9694
assert avro_df is not None
97-
98-
99-
def test_arrow_c_stream_large_dataset(ctx):
100-
"""DataFrame.__arrow_c_stream__ yields batches incrementally.
101-
102-
This test constructs a DataFrame that would be far larger than available
103-
memory if materialized. The ``__arrow_c_stream__`` method should expose a
104-
stream of record batches without collecting the full dataset, so reading a
105-
handful of batches should not exhaust process memory.
106-
"""
107-
# Create a very large DataFrame using range; this would be terabytes if collected
108-
df = range_table(ctx, 0, 1 << 40)
109-
110-
reader = pa.RecordBatchReader._import_from_c_capsule(df.__arrow_c_stream__())
111-
112-
# Track RSS before consuming batches
113-
psutil = pytest.importorskip("psutil")
114-
process = psutil.Process()
115-
start_rss = process.memory_info().rss
116-
117-
for _ in range(5):
118-
batch = reader.read_next_batch()
119-
assert batch is not None
120-
assert len(batch) > 0
121-
current_rss = process.memory_info().rss
122-
# Ensure memory usage hasn't grown substantially (>50MB)
123-
assert current_rss - start_rss < 50 * 1024 * 1024
124-
125-
126-
def test_table_from_batches_stream(ctx, fail_collect):
127-
df = range_table(ctx, 0, 10)
128-
129-
table = pa.Table.from_batches(df)
130-
assert table.shape == (10, 1)
131-
assert table.column_names == ["value"]

0 commit comments

Comments
 (0)