Repository navigation
Add PyWayang load_collection using literal JSON input #870
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
|
||
| 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: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What is this patch doing?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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]) | ||
There was a problem hiding this comment.
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.