Skip to content

Remove open_async usage in put raw data #2998

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 11 additions & 27 deletions flytekit/core/data_persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,6 @@
) -> Union[AsyncFileSystem, fsspec.AbstractFileSystem]:
protocol = get_protocol(path)
loop = asyncio.get_running_loop()

return self.get_filesystem(protocol, anonymous=anonymous, path=path, asynchronous=True, loop=loop, **kwargs)

def get_filesystem_for_path(self, path: str = "", anonymous: bool = False, **kwargs) -> fsspec.AbstractFileSystem:
Expand Down Expand Up @@ -425,45 +424,30 @@

# raw bytes
if isinstance(lpath, bytes):
fs = await self.get_async_filesystem_for_path(to_path)
if isinstance(fs, AsyncFileSystem):
async with fs.open_async(to_path, "wb", **kwargs) as s:
s.write(lpath)
else:
with fs.open(to_path, "wb", **kwargs) as s:
s.write(lpath)

fs = self.get_filesystem_for_path(to_path)
with fs.open(to_path, "wb", **kwargs) as s:
s.write(lpath)

Check warning on line 429 in flytekit/core/data_persistence.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/data_persistence.py#L427-L429

Added lines #L427 - L429 were not covered by tests
return to_path

# If lpath is a buffered reader of some kind
if isinstance(lpath, io.BufferedReader) or isinstance(lpath, io.BytesIO):
if not lpath.readable():
raise FlyteAssertion("Buffered reader must be readable")
fs = await self.get_async_filesystem_for_path(to_path)
fs = self.get_filesystem_for_path(to_path)

Check warning on line 436 in flytekit/core/data_persistence.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/data_persistence.py#L436

Added line #L436 was not covered by tests
lpath.seek(0)
if isinstance(fs, AsyncFileSystem):
async with fs.open_async(to_path, "wb", **kwargs) as s:
while data := lpath.read(read_chunk_size_bytes):
s.write(data)
else:
with fs.open(to_path, "wb", **kwargs) as s:
while data := lpath.read(read_chunk_size_bytes):
s.write(data)
with fs.open(to_path, "wb", **kwargs) as s:

Check warning on line 438 in flytekit/core/data_persistence.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/data_persistence.py#L438

Added line #L438 was not covered by tests
while data := lpath.read(read_chunk_size_bytes):
s.write(data)

Check warning on line 440 in flytekit/core/data_persistence.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/data_persistence.py#L440

Added line #L440 was not covered by tests
return to_path

if isinstance(lpath, io.StringIO):
if not lpath.readable():
raise FlyteAssertion("Buffered reader must be readable")
fs = await self.get_async_filesystem_for_path(to_path)
fs = self.get_filesystem_for_path(to_path)

Check warning on line 446 in flytekit/core/data_persistence.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/data_persistence.py#L446

Added line #L446 was not covered by tests
lpath.seek(0)
if isinstance(fs, AsyncFileSystem):
async with fs.open_async(to_path, "wb", **kwargs) as s:
while data_str := lpath.read(read_chunk_size_bytes):
s.write(data_str.encode(encoding))
else:
with fs.open(to_path, "wb", **kwargs) as s:
while data_str := lpath.read(read_chunk_size_bytes):
s.write(data_str.encode(encoding))
with fs.open(to_path, "wb", **kwargs) as s:

Check warning on line 448 in flytekit/core/data_persistence.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/data_persistence.py#L448

Added line #L448 was not covered by tests
while data_str := lpath.read(read_chunk_size_bytes):
s.write(data_str.encode(encoding))

Check warning on line 450 in flytekit/core/data_persistence.py

View check run for this annotation

Codecov / codecov/patch

flytekit/core/data_persistence.py#L450

Added line #L450 was not covered by tests
return to_path

raise FlyteAssertion(f"Unsupported lpath type {type(lpath)}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ def encode(
df.to_parquet(output_bytes)

if structured_dataset.uri is not None:
output_bytes.seek(0)
fs = ctx.file_access.get_filesystem_for_path(path=structured_dataset.uri)
with fs.open(structured_dataset.uri, "wb") as s:
s.write(output_bytes)
s.write(output_bytes.read())
output_uri = structured_dataset.uri
else:
remote_fn = "00000" # 00000 is our default unnamed parquet filename
Expand Down
27 changes: 26 additions & 1 deletion plugins/flytekit-polars/tests/test_polars_plugin_sd.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pytest
from flytekitplugins.polars.sd_transformers import PolarsDataFrameRenderer
from typing_extensions import Annotated
from packaging import version
import numpy as np
from polars.testing import assert_frame_equal

from flytekit import kwtypes, task, workflow
Expand Down Expand Up @@ -134,3 +134,28 @@ def consume_sd_return_sd(sd: StructuredDataset) -> StructuredDataset:
opened_sd = opened_sd.collect()

assert_frame_equal(opened_sd, polars_df)


def test_with_uri():
temp_file = tempfile.mktemp()

@task
def random_dataframe(num_rows: int) -> StructuredDataset:
feature_1_list = np.random.randint(low=100, high=999, size=(num_rows,))
feature_2_list = np.random.normal(loc=0, scale=1, size=(num_rows, ))
pl_df = pl.DataFrame({'protein_length': feature_1_list,
'protein_feature': feature_2_list})
sd = StructuredDataset(dataframe=pl_df, uri=temp_file)
return sd

@task
def consume(df: pd.DataFrame):
print(df.head(5))
print(df.describe())

@workflow
def my_wf(num_rows: int):
pl = random_dataframe(num_rows=num_rows)
consume(pl)

my_wf(num_rows=100)
18 changes: 17 additions & 1 deletion tests/flytekit/unit/core/test_data_persistence.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import io
import os
import fsspec
import pathlib
import random
import string
import sys
import tempfile

import fsspec
import mock
import pytest
from azure.identity import ClientSecretCredential, DefaultAzureCredential

from flytekit.configuration import Config
from flytekit.core.data_persistence import FileAccessProvider
from flytekit.core.local_fsspec import FlyteLocalFileSystem

Expand Down Expand Up @@ -207,3 +208,18 @@ def __init__(self, *args, **kwargs):

fp = FileAccessProvider("/tmp", "s3://my-bucket")
fp.get_filesystem("testgetfs", test_arg="test_arg")


@pytest.mark.sandbox_test
def test_put_raw_data_bytes():
dc = Config.for_sandbox().data_config
raw_output = f"s3://my-s3-bucket/"
provider = FileAccessProvider(local_sandbox_dir="/tmp/unittest", raw_output_prefix=raw_output, data_config=dc)
prefix = provider.get_random_string()
provider.put_raw_data(lpath=b"hello", upload_prefix=prefix, file_name="hello_bytes")
provider.put_raw_data(lpath=io.BytesIO(b"hello"), upload_prefix=prefix, file_name="hello_bytes_io")
provider.put_raw_data(lpath=io.StringIO("hello"), upload_prefix=prefix, file_name="hello_string_io")

fs = provider.get_filesystem("s3")
listing = fs.ls(f"{raw_output}{prefix}/")
assert len(listing) == 3
Loading