carloea2 commented on code in PR #8433:
URL: https://github.com/apache/texera/pull/8433#discussion_r4029786950


##########
amber/src/main/python/pytexera/workflow/codec.py:
##########
@@ -0,0 +1,130 @@
+# 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.
+
+"""Cloudpickle transport for explicit workflow boundary payloads."""
+
+from __future__ import annotations
+
+import pickle
+from dataclasses import dataclass
+
+import cloudpickle
+
+
+@dataclass(frozen=True, order=True)
+class BoundaryPayload:
+    """One boundary contract, its path-present fields, and encoded values."""
+
+    boundary_id: str
+    fields: tuple[str, ...]
+    present: tuple[str, ...]
+    payload: bytes
+
+    def __post_init__(self) -> None:
+        if not self.boundary_id:
+            raise ValueError("boundary ID must be nonempty")
+        if self.fields != tuple(sorted(set(self.fields))) or any(
+            not field.isidentifier() for field in self.fields
+        ):
+            raise ValueError("boundary fields must be canonical Python names")
+        if self.present != tuple(
+            field for field in self.fields if field in frozenset(self.present)
+        ):
+            raise ValueError("present fields must be a canonical contract 
subset")
+        if not isinstance(self.payload, bytes):
+            raise TypeError("boundary payload must be bytes")
+
+
+@dataclass(frozen=True)
+class WorkflowEnvelope:
+    """All selected boundary payloads for one independent execution key."""
+
+    execution_key: str
+    boundaries: tuple[BoundaryPayload, ...]
+
+    def __post_init__(self) -> None:
+        if not self.execution_key:
+            raise ValueError("execution key must be nonempty")
+        if not isinstance(self.boundaries, tuple) or any(
+            not isinstance(row, BoundaryPayload) for row in self.boundaries
+        ):
+            raise TypeError("workflow boundaries must be a typed tuple")
+        ids = tuple(row.boundary_id for row in self.boundaries)
+        if ids != tuple(sorted(set(ids))):
+            raise ValueError("workflow boundaries must be canonical and 
unique")
+
+
+def encode_boundary(
+    boundary_id: str,
+    fields: tuple[str, ...],
+    values: tuple[object, ...],
+    *,
+    present: tuple[str, ...] | None = None,
+) -> BoundaryPayload:
+    """Encode values present on this path under one selected field contract."""
+
+    present = fields if present is None else present
+    if len(present) != len(values):
+        raise ValueError("present boundary fields and values must have equal 
length")
+    payload = cloudpickle.dumps(values, protocol=pickle.HIGHEST_PROTOCOL)
+    return BoundaryPayload(boundary_id, fields, present, payload)
+
+
+def decode_boundary(
+    boundary: BoundaryPayload,
+    fields: tuple[str, ...],
+) -> tuple[object, ...]:
+    """Decode a payload only under its exact selected field contract."""
+
+    if boundary.fields != fields:
+        raise ValueError("boundary fields do not match the requested contract")
+    values = cloudpickle.loads(boundary.payload)
+    if not isinstance(values, tuple) or len(values) != len(boundary.present):
+        raise ValueError("decoded boundary payload has an invalid shape")
+    return values
+
+
+def dumps_envelope(envelope: WorkflowEnvelope) -> bytes:
+    """Validate and encode a workflow envelope."""
+
+    if not isinstance(envelope, WorkflowEnvelope):
+        raise TypeError("envelope codec requires WorkflowEnvelope")
+    return cloudpickle.dumps(envelope, protocol=pickle.HIGHEST_PROTOCOL)
+
+
+def loads_envelope(payload: bytes) -> WorkflowEnvelope:
+    """Decode and type-check one workflow envelope."""
+
+    envelope = cloudpickle.loads(payload)

Review Comment:
   Fixed in a90fcd2e8. loads_envelope now revalidates the envelope and every 
nested boundary after unpickling; dumps_envelope validates them before 
serialization too. Added tests that mutate metadata before pickling to verify 
constructor bypass is caught. This remains a trusted-payload codec, not a safe 
loader for untrusted pickle data.



##########
amber/src/main/python/pytexera/workflow/codec.py:
##########
@@ -0,0 +1,130 @@
+# 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.
+
+"""Cloudpickle transport for explicit workflow boundary payloads."""
+
+from __future__ import annotations
+
+import pickle
+from dataclasses import dataclass
+
+import cloudpickle
+
+
+@dataclass(frozen=True, order=True)
+class BoundaryPayload:
+    """One boundary contract, its path-present fields, and encoded values."""
+
+    boundary_id: str
+    fields: tuple[str, ...]
+    present: tuple[str, ...]
+    payload: bytes
+
+    def __post_init__(self) -> None:
+        if not self.boundary_id:

Review Comment:
   Added an explicit string check before the nonempty boundary ID check in 
a90fcd2e8. Tests cover non-string values, empty strings, and a valid Unicode ID.



##########
amber/src/main/python/pytexera/workflow/codec.py:
##########
@@ -0,0 +1,130 @@
+# 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.
+
+"""Cloudpickle transport for explicit workflow boundary payloads."""
+
+from __future__ import annotations
+
+import pickle
+from dataclasses import dataclass
+
+import cloudpickle
+
+
+@dataclass(frozen=True, order=True)
+class BoundaryPayload:
+    """One boundary contract, its path-present fields, and encoded values."""
+
+    boundary_id: str
+    fields: tuple[str, ...]
+    present: tuple[str, ...]
+    payload: bytes
+
+    def __post_init__(self) -> None:
+        if not self.boundary_id:
+            raise ValueError("boundary ID must be nonempty")
+        if self.fields != tuple(sorted(set(self.fields))) or any(
+            not field.isidentifier() for field in self.fields
+        ):
+            raise ValueError("boundary fields must be canonical Python names")
+        if self.present != tuple(
+            field for field in self.fields if field in frozenset(self.present)
+        ):
+            raise ValueError("present fields must be a canonical contract 
subset")
+        if not isinstance(self.payload, bytes):
+            raise TypeError("boundary payload must be bytes")
+
+
+@dataclass(frozen=True)
+class WorkflowEnvelope:
+    """All selected boundary payloads for one independent execution key."""
+
+    execution_key: str
+    boundaries: tuple[BoundaryPayload, ...]
+
+    def __post_init__(self) -> None:
+        if not self.execution_key:

Review Comment:
   Added the same explicit string check for execution_key in a90fcd2e8, 
including validation after unpickling. Non-string and empty keys are rejected; 
Unicode keys round-trip successfully.



##########
amber/src/test/python/pytexera/workflow/test_codec.py:
##########
@@ -0,0 +1,82 @@
+# 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 pytest
+from pytexera.workflow.codec import (
+    BoundaryPayload,
+    WorkflowEnvelope,
+    decode_boundary,
+    dumps_envelope,
+    encode_boundary,
+    loads_envelope,
+    merge_envelopes,
+)
+
+
+def test_boundary_cloudpickle_preserves_aliases_and_cycles() -> None:
+    shared = []
+    shared.append(shared)
+
+    boundary = encode_boundary("edge", ("left", "right"), (shared, shared))
+    values = decode_boundary(boundary, ("left", "right"))
+
+    assert values[0] is values[1]
+    assert values[0][0] is values[0]
+
+
+def test_envelope_round_trip_contains_only_explicit_boundaries() -> None:
+    boundary = encode_boundary("edge", ("value",), ({"large": [1, 2, 3]},))
+    envelope = WorkflowEnvelope("run-1", (boundary,))
+
+    decoded = loads_envelope(dumps_envelope(envelope))
+
+    assert decoded == envelope
+    assert decoded.boundaries[0].fields == ("value",)
+
+
+def test_decode_rejects_field_contract_mismatch() -> None:
+    boundary = encode_boundary("edge", ("value",), (1,))
+
+    with pytest.raises(ValueError, match="fields"):
+        decode_boundary(boundary, ("other",))
+
+
+def test_boundary_cloudpickle_preserves_an_absent_selected_field() -> None:
+    """The wire contract and the values present on one path remain distinct."""
+
+    boundary = encode_boundary(
+        "edge",
+        ("left", "right"),
+        (41,),
+        present=("left",),
+    )
+
+    assert boundary.fields == ("left", "right")
+    assert boundary.present == ("left",)
+    assert decode_boundary(boundary, ("left", "right")) == (41,)
+
+
+def test_envelope_rejects_duplicate_boundaries_and_cross_key_merge() -> None:
+    boundary = BoundaryPayload("edge", ("value",), ("value",), b"payload")
+    with pytest.raises(ValueError, match="canonical"):
+        WorkflowEnvelope("run", (boundary, boundary))
+
+    with pytest.raises(ValueError, match="execution key"):
+        merge_envelopes(
+            WorkflowEnvelope("left", ()),
+            WorkflowEnvelope("right", ()),
+        )

Review Comment:
   Added both cases in a90fcd2e8: merging two valid envelopes with the same key 
and overlapping boundary IDs rejects the merge even when their values differ. A 
successful disjoint merge verifies canonical ID ordering and decodes both 
values to confirm neither payload was lost.



##########
amber/src/main/python/pytexera/workflow/codec.py:
##########
@@ -0,0 +1,130 @@
+# 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.
+
+"""Cloudpickle transport for explicit workflow boundary payloads."""
+
+from __future__ import annotations
+
+import pickle
+from dataclasses import dataclass
+
+import cloudpickle
+
+
+@dataclass(frozen=True, order=True)
+class BoundaryPayload:
+    """One boundary contract, its path-present fields, and encoded values."""
+
+    boundary_id: str
+    fields: tuple[str, ...]
+    present: tuple[str, ...]
+    payload: bytes
+
+    def __post_init__(self) -> None:
+        if not self.boundary_id:
+            raise ValueError("boundary ID must be nonempty")
+        if self.fields != tuple(sorted(set(self.fields))) or any(
+            not field.isidentifier() for field in self.fields
+        ):
+            raise ValueError("boundary fields must be canonical Python names")
+        if self.present != tuple(
+            field for field in self.fields if field in frozenset(self.present)
+        ):
+            raise ValueError("present fields must be a canonical contract 
subset")
+        if not isinstance(self.payload, bytes):
+            raise TypeError("boundary payload must be bytes")
+
+
+@dataclass(frozen=True)
+class WorkflowEnvelope:
+    """All selected boundary payloads for one independent execution key."""
+
+    execution_key: str
+    boundaries: tuple[BoundaryPayload, ...]
+
+    def __post_init__(self) -> None:
+        if not self.execution_key:
+            raise ValueError("execution key must be nonempty")
+        if not isinstance(self.boundaries, tuple) or any(
+            not isinstance(row, BoundaryPayload) for row in self.boundaries
+        ):
+            raise TypeError("workflow boundaries must be a typed tuple")
+        ids = tuple(row.boundary_id for row in self.boundaries)
+        if ids != tuple(sorted(set(ids))):
+            raise ValueError("workflow boundaries must be canonical and 
unique")
+
+
+def encode_boundary(
+    boundary_id: str,
+    fields: tuple[str, ...],
+    values: tuple[object, ...],
+    *,
+    present: tuple[str, ...] | None = None,
+) -> BoundaryPayload:
+    """Encode values present on this path under one selected field contract."""
+
+    present = fields if present is None else present
+    if len(present) != len(values):
+        raise ValueError("present boundary fields and values must have equal 
length")
+    payload = cloudpickle.dumps(values, protocol=pickle.HIGHEST_PROTOCOL)

Review Comment:
   Fixed in a90fcd2e8. encode_boundary rejects non-tuple values with TypeError 
before calling cloudpickle.dumps. The regression test replaces the serializer 
with a failure sentinel to verify it is never called for those invalid inputs.



##########
amber/src/main/python/pytexera/workflow/codec.py:
##########
@@ -0,0 +1,130 @@
+# 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.
+
+"""Cloudpickle transport for explicit workflow boundary payloads."""
+
+from __future__ import annotations
+
+import pickle
+from dataclasses import dataclass
+
+import cloudpickle
+
+
+@dataclass(frozen=True, order=True)
+class BoundaryPayload:
+    """One boundary contract, its path-present fields, and encoded values."""
+
+    boundary_id: str
+    fields: tuple[str, ...]
+    present: tuple[str, ...]
+    payload: bytes
+
+    def __post_init__(self) -> None:
+        if not self.boundary_id:
+            raise ValueError("boundary ID must be nonempty")
+        if self.fields != tuple(sorted(set(self.fields))) or any(
+            not field.isidentifier() for field in self.fields
+        ):
+            raise ValueError("boundary fields must be canonical Python names")
+        if self.present != tuple(
+            field for field in self.fields if field in frozenset(self.present)
+        ):
+            raise ValueError("present fields must be a canonical contract 
subset")
+        if not isinstance(self.payload, bytes):
+            raise TypeError("boundary payload must be bytes")
+
+
+@dataclass(frozen=True)
+class WorkflowEnvelope:
+    """All selected boundary payloads for one independent execution key."""
+
+    execution_key: str
+    boundaries: tuple[BoundaryPayload, ...]
+
+    def __post_init__(self) -> None:
+        if not self.execution_key:
+            raise ValueError("execution key must be nonempty")
+        if not isinstance(self.boundaries, tuple) or any(
+            not isinstance(row, BoundaryPayload) for row in self.boundaries
+        ):
+            raise TypeError("workflow boundaries must be a typed tuple")
+        ids = tuple(row.boundary_id for row in self.boundaries)
+        if ids != tuple(sorted(set(ids))):
+            raise ValueError("workflow boundaries must be canonical and 
unique")
+
+
+def encode_boundary(
+    boundary_id: str,
+    fields: tuple[str, ...],
+    values: tuple[object, ...],
+    *,
+    present: tuple[str, ...] | None = None,
+) -> BoundaryPayload:
+    """Encode values present on this path under one selected field contract."""
+
+    present = fields if present is None else present
+    if len(present) != len(values):
+        raise ValueError("present boundary fields and values must have equal 
length")
+    payload = cloudpickle.dumps(values, protocol=pickle.HIGHEST_PROTOCOL)
+    return BoundaryPayload(boundary_id, fields, present, payload)
+
+
+def decode_boundary(
+    boundary: BoundaryPayload,
+    fields: tuple[str, ...],
+) -> tuple[object, ...]:
+    """Decode a payload only under its exact selected field contract."""
+
+    if boundary.fields != fields:
+        raise ValueError("boundary fields do not match the requested contract")
+    values = cloudpickle.loads(boundary.payload)

Review Comment:
   Documented the existing exception contract in a90fcd2e8: pickle/loading 
exceptions propagate unchanged. Added tests for EOFError on empty bytes and 
pickle.UnpicklingError on invalid opcodes in both decoders. No exception 
wrapping is introduced.



##########
amber/src/main/python/pytexera/workflow/codec.py:
##########
@@ -0,0 +1,130 @@
+# 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.
+
+"""Cloudpickle transport for explicit workflow boundary payloads."""
+
+from __future__ import annotations
+
+import pickle
+from dataclasses import dataclass
+
+import cloudpickle
+
+
+@dataclass(frozen=True, order=True)

Review Comment:
   Removed order=True in a90fcd2e8. merge_envelopes still sorts explicitly by 
boundary_id. The test verifies canonical merge order and that comparing 
BoundaryPayload objects with < is unsupported. All 28 codec tests pass locally 
with python -m pytest -q src/test/python/pytexera/workflow/test_codec.py (from 
amber).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to