Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
23 changes: 23 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,25 @@ configuration.set_property("wayang.api.python.port", "8080")
The same values can be supplied through environment variables:
`WAYANG_API_URL`, or `WAYANG_API_HOST` and `WAYANG_API_PORT`.

## In-memory collections

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a very long README addition for just a load collection operator.

`load_collection()` creates a `DataQuanta` from a Python list, tuple, or NumPy
array. It copies the input, preserving order and nesting; empty inputs are valid.
Supported elements are strings, booleans, signed 64-bit integers, finite floats,
and nested lists, tuples, or arrays. NumPy boolean, integer, float16/32/64, and
Unicode values are supported within the same limits. Unsupported values raise
`TypeError` or `ValueError` before execution.

```python
import numpy as np
from pywy.dataquanta import WayangContext
from pywy.platforms.java import JavaPlugin

ctx = WayangContext().register({JavaPlugin})
ctx.load_collection([1, 2, 3]).store_textfile("file:///tmp/numbers.txt")
ctx.load_collection(np.array([1.5, 2.5])).store_textfile("file:///tmp/floats.txt")
```

## Docker

The Python API can be run with the Wayang REST API as a separate container.
Expand Down Expand Up @@ -148,3 +167,7 @@ docker network rm wayang-python

### Testing python code
You can run the python tests by using pytest, the requirements for the tests are listed in `python/src/pywy/requirements.txt`. To run the tests navigate to the base wayang folder, e.g. `/var/www/html` and run `pytest -s python/src/pywy` if you need to pass a specific configuration for your use case you can also add a config flag `pytest -s --config=pathToYourConfig python/src/pywy/`

Collection unit tests run without a backend. See the setup instructions in
[`test_load_collection_integration.py`](src/pywy/tests/test_load_collection_integration.py)
for running the collection tests against a local REST backend.
5 changes: 4 additions & 1 deletion python/src/pywy/core/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ def serialize(self, operator):
if hasattr(operator, "output_type") and operator.output_type is not None:
json_operator["data"]["outputType"] = ndim_from_type(operator.output_type).to_json()

if operator.json_name == "filter":
if operator.json_name == "inputCollection":
json_operator["data"]["values"] = operator.values

elif operator.json_name == "filter":
json_operator["data"]["udf"] = base64.b64encode(cloudpickle.dumps(operator.use_predicate)).decode('utf-8')

elif operator.json_name == "reduceBy":
Expand Down
20 changes: 19 additions & 1 deletion python/src/pywy/dataquanta.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
# limitations under the License.
#

from typing import Set, List, Optional, cast
from typing import Set, List, Optional, Tuple, Union, cast

from numpy import ndarray

from pywy.core.core import Plugin, PywyPlan
from pywy.operators.base import PO_T
Expand Down Expand Up @@ -56,6 +58,22 @@ def unregister(self, *plugins: Plugin):
def textfile(self, file_path: str) -> "DataQuanta[str]":
return DataQuanta(self, TextFileSource(file_path))

def load_collection(self, collection: Union[List[T], Tuple[T, ...], ndarray]) -> "DataQuanta[T]":
"""Create a source from a snapshot of a list, tuple, or NumPy array.

Values may be strings, booleans, signed 64-bit integers, finite floats,
or nested lists/tuples/arrays (containers become lists). NumPy boolean,
integer, float16/32/64, and Unicode scalars are converted to Python values.
Arrays must have at least one dimension at the top level; nested scalar
arrays become scalar values. Empty collections are valid.
Other values, including None, mappings, sets, and cyclic containers,
raise TypeError or ValueError before a plan is submitted.

As with other sources, the current Python worker passes records to UDFs
as strings. Numeric UDFs must convert their input with int() or float().
"""
return DataQuanta(self, CollectionSource(collection))

def parquet(
self, file_path: str, projection: Optional[List[str]] = None, column_names: Optional[List[str]] = None
) -> "DataQuanta[Record]":
Expand Down
3 changes: 2 additions & 1 deletion python/src/pywy/operators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pywy.operators.binary import BinaryToUnaryOperator, JoinOperator, DLTrainingOperator, PredictOperator, \
CartesianOperator
from pywy.operators.sink import TextFileSink, SinkOperator
from pywy.operators.source import TextFileSource, ParquetSource, SourceUnaryOperator
from pywy.operators.source import CollectionSource, TextFileSource, ParquetSource, SourceUnaryOperator
from pywy.operators.unary import UnaryToUnaryOperator, FilterOperator, MapOperator, FlatmapOperator, \
ReduceByKeyOperator, SortOperator

Expand All @@ -29,6 +29,7 @@
BinaryToUnaryOperator,
TextFileSink,
TextFileSource,
CollectionSource,
ParquetSource,
FilterOperator,
SinkOperator,
Expand Down
49 changes: 49 additions & 0 deletions python/src/pywy/operators/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
# limitations under the License.
#

import math
from typing import List, Optional

import numpy as np

from pywy.operators.base import PywyOperator
from pywy.basic.data.record import Record
from pywy.types import GenericTco
Expand Down Expand Up @@ -44,6 +47,52 @@ def __repr__(self):
return super().__repr__()


class CollectionSource(SourceUnaryOperator):
def __init__(self, collection):
# Empty and heterogeneous collections use the backend's generic type.
super().__init__('Collection', output_type=None)
self.json_name = "inputCollection"
if type(collection) not in (list, tuple, np.ndarray):
raise TypeError("load_collection expects a list, tuple, or NumPy array")
if type(collection) is np.ndarray and collection.ndim == 0:
raise TypeError("load_collection expects a NumPy array with at least one dimension")
self.values = self._snapshot(collection, set(), "collection")

@staticmethod
def _snapshot(value, ancestors, path):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add support to handle NumPy values?

# Apply the same JSON type and range checks after NumPy conversion.
if isinstance(value, np.generic) and value.dtype.kind in "biufU":
value = value.item()
if type(value) is np.ndarray:
if value.dtype.kind not in "biufUO" or (value.dtype.kind == "f" and value.dtype.itemsize > 8):
raise TypeError(f"{path}: unsupported NumPy dtype {value.dtype}")
if type(value) in (str, bool):
return value
if type(value) is int:
if not -(2 ** 63) <= value < 2 ** 63:
raise ValueError(f"{path}: integers must fit in signed 64 bits")
return value
if type(value) is float:
if not math.isfinite(value):
raise ValueError(f"{path}: floats must be finite")
return value
if type(value) in (list, tuple, np.ndarray):
if id(value) in ancestors:
raise ValueError(f"{path}: cyclic collections are not supported")
ancestors.add(id(value))
items = value.tolist() if type(value) is np.ndarray else value
if type(value) is np.ndarray and value.ndim == 0:
result = CollectionSource._snapshot(items, ancestors, path)
else:
result = [
CollectionSource._snapshot(item, ancestors, f"{path}[{index}]")
for index, item in enumerate(items)
]
ancestors.remove(id(value))
return result
raise TypeError(f"{path}: unsupported collection value of type {type(value).__name__}")


class TextFileSource(SourceUnaryOperator):
path: str
json_name: str
Expand Down
193 changes: 193 additions & 0 deletions python/src/pywy/tests/test_load_collection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import base64
import json
from unittest.mock import patch

import cloudpickle
import numpy as np
import pytest

from pywy.dataquanta import DataQuanta, WayangContext
from pywy.operators import CollectionSource, SourceUnaryOperator
from pywy.platforms.java import JavaPlugin


@pytest.mark.parametrize("values", [
[1, -2, 0, -(2 ** 63), 2 ** 63 - 1],
[1.5, -0.0, 1e-300, 1e300],
['quotes " and \\', "line\nfeed\ttab", "雪 😀", "", '${System.exit(1)}'],
[],
[True, False],
[[1, 2], [], [3, ["nested", False]]],
[1, "two", 3.5, True],
])
def test_collection_plan(values):
context = WayangContext().register({JavaPlugin})
data = context.load_collection(values)
assert isinstance(data, DataQuanta)
assert data.context is context
assert isinstance(data.operator, SourceUnaryOperator)
assert data.operator.inputs == 0
assert data.operator.outputs == 1

# Capture the submitted JSON without requiring a running REST server.
# Actual HTTP execution and file contents are covered by the integration tests.
with patch("pywy.core.core.requests.post") as post:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this patch doing?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the patch mocks requests.post so this unit test can inspect the generated JSON plan without needing a running REST server. Separate integration tests send real requests to the Wayang backend and verify the output files. I’ve added a comment explaining this and an assertion that exactly one request is submitted.

data.store_textfile("file:///tmp/collection.txt")

post.assert_called_once()
plan = json.loads(json.dumps(post.call_args.kwargs["json"], allow_nan=False))
assert plan["context"]["origin"] == "python"
assert plan["context"]["platforms"] == ["java"]
source, sink = plan["operators"]
assert source == {
"id": 1, "operatorName": "inputCollection", "cat": "input",
"input": [], "output": [2], "data": {"values": values},
}
assert sink["operatorName"] == "textFileOutput"
assert sink["input"] == [1]
assert sink["data"]["filename"] == "file:///tmp/collection.txt"


def test_snapshot_and_tuples():
nested = [1, (2, 3)]
values = [nested, nested]
source = CollectionSource(values)
nested.append(4)
values.clear()
assert source.values == [[1, [2, 3]], [1, [2, 3]]]
assert CollectionSource((1, 2)).values == [1, 2]


@pytest.mark.parametrize("values", ["abc", b"abc", {1, 2}, {"a": 1}, None, iter([1, 2])])
def test_reject_unordered_or_non_collection_inputs(values):
with pytest.raises(TypeError, match="expects a list, tuple, or NumPy array"):
WayangContext().load_collection(values)


@pytest.mark.parametrize("value", [None, {}, {1}, b"bytes", complex(1, 2), object()])
def test_reject_unsupported_values(value):
with pytest.raises(TypeError, match=r"collection\[0\]\[0\]: unsupported"):
WayangContext().load_collection([[value]])


@pytest.mark.parametrize("value", [-(2 ** 63) - 1, 2 ** 63, float("nan"), float("inf"), -float("inf")])
def test_reject_out_of_range_values(value):
with pytest.raises(ValueError, match=r"collection\[0\]"):
WayangContext().load_collection([value])


def test_reject_cycles():
values = []
values.append(values)
with pytest.raises(ValueError, match="cyclic"):
WayangContext().load_collection(values)


def test_collection_transformation():
# Inspect the serialized pipeline; only the HTTP request is mocked.
with patch("pywy.core.core.requests.post") as post:
(WayangContext().register({JavaPlugin}).load_collection([3, 1, 2])
.filter(lambda value: int(value) > 1, str)
.map(lambda value: int(value) * 2, str, int)
.store_textfile("file:///tmp/doubled.txt"))
source, transform, sink = post.call_args.kwargs["json"]["operators"]
assert source["output"] == [transform["id"]]
assert transform["input"] == [source["id"]]
assert transform["output"] == [sink["id"]]
assert sink["input"] == [transform["id"]]
assert transform["operatorName"] == "mapPartitions"
udf = cloudpickle.loads(base64.b64decode(transform["data"]["udf"]))
assert list(udf(iter(["3", "1", "2"]))) == [6, 4]


@pytest.mark.parametrize("values, expected", [
(np.array([1, -2], dtype=np.int32), [1, -2]),
(np.array([-(2 ** 63), 2 ** 63 - 1], dtype=np.int64), [-(2 ** 63), 2 ** 63 - 1]),
(np.array([0, 2 ** 63 - 1], dtype=np.uint64), [0, 2 ** 63 - 1]),
(np.array([1.5, -0.0], dtype=np.float16), [1.5, -0.0]),
(np.array([1.5, 2.25], dtype=np.float32), [1.5, 2.25]),
(np.array([1.23456789012345], dtype=np.float64), [1.23456789012345]),
(np.array([True, False]), [True, False]),
(np.array(['"quoted"', "雪\n\\"]), ['"quoted"', "雪\n\\"]),
(np.array([[1, 2], [3, 4]]).T, [[1, 3], [2, 4]]),
(np.arange(6)[::2], [0, 2, 4]),
(np.empty((0, 2)), []),
(np.empty((2, 0)), [[], []]),
([np.int64(1), np.float32(1.5), np.bool_(True), np.str_("雪")], [1, 1.5, True, "雪"]),
([np.array(3), (np.array([4, 5]),)], [3, [[4, 5]]]),
(np.array([1, "two", [np.float64(3.5)]], dtype=object), [1, "two", [3.5]]),
])
def test_numpy_collection_plan(values, expected):
# Capture the JSON request, including conversion of every NumPy element.
with patch("pywy.core.core.requests.post") as post:
WayangContext().register({JavaPlugin}).load_collection(values).store_textfile("file:///tmp/numpy.txt")
post.assert_called_once()
actual = post.call_args.kwargs["json"]["operators"][0]["data"]["values"]
assert json.dumps(actual, allow_nan=False) == json.dumps(expected, allow_nan=False)


def test_numpy_snapshot():
array = np.array([[1, 2], [3, 4]])
data = WayangContext().load_collection([array, array])
array[:] = 0
assert data.operator.values == [[[1, 2], [3, 4]], [[1, 2], [3, 4]]]


@pytest.mark.parametrize("values", [np.int64(1), np.array(1)])
def test_reject_scalar_collection(values):
with pytest.raises(TypeError, match="load_collection expects"):
WayangContext().load_collection(values)


@pytest.mark.parametrize("value", [
np.complex64(1j), np.bytes_(b"bytes"), np.datetime64(1, "ns"),
np.timedelta64(1, "ns"), np.array([np.datetime64(1, "ns")]),
np.array([1j]), np.array([], dtype=complex),
np.array([("a", 1)], dtype=[("name", "U1"), ("value", "i4")]),
np.ma.array([1, 2], mask=[False, True]),
])
def test_reject_unsupported_numpy_values(value):
with pytest.raises(TypeError, match=r"collection\[0\]: unsupported"):
WayangContext().load_collection([value])


@pytest.mark.parametrize("value", [
np.uint64(2 ** 63), np.float32("nan"), np.float64("inf"),
np.array([np.uint64(2 ** 63)]), np.array([float("-inf")]),
])
def test_reject_out_of_range_numpy_values(value):
with pytest.raises(ValueError, match=r"collection\[0\]"):
WayangContext().load_collection([value])


@pytest.mark.parametrize("shape", [(1,), ()])
def test_reject_numpy_object_cycles(shape):
array = np.empty(shape, dtype=object)
array.flat[0] = array
with pytest.raises(ValueError, match="cyclic"):
WayangContext().load_collection([array])


def test_reject_extended_precision_numpy_values():
if np.dtype(np.longdouble).itemsize <= 8:
pytest.skip("longdouble has no additional precision on this platform")
for value in (np.longdouble(1), np.array([1], dtype=np.longdouble)):
with pytest.raises(TypeError, match="unsupported"):
WayangContext().load_collection([value])
Loading