carloea2 commented on code in PR #8357: URL: https://github.com/apache/texera/pull/8357#discussion_r4253803271
########## workflow-compiling-service/src/test/scala/org/apache/texera/amber/translator/verify/PyOpExecHarnessSpec.scala: ########## @@ -0,0 +1,434 @@ +/* + * 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. + */ + +package org.apache.texera.amber.translator.verify + +import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, LargeBinary, Schema, Tuple} +import org.apache.texera.amber.core.workflow.{InputPort, OutputPort, PortIdentity} +import org.apache.texera.amber.operator.PythonOperatorDescriptor +import org.apache.texera.amber.operator.metadata.{OperatorGroupConstants, OperatorInfo} +import org.apache.texera.amber.translator.verify.tags.IntegrationTest +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import java.nio.file.Files +import java.sql.Timestamp +import java.util.Base64 +import scala.sys.process._ + +/** The reference path's own behaviour, where it can differ from the worker's. + * + * Tagged @IntegrationTest: the harness forks Python. + */ +@IntegrationTest +class PyOpExecHarnessSpec extends AnyFlatSpec with Matchers { + + /** Yields one dict twice, changing it in between. `DataProcessor` reads a + * yield where it happens, so the engine records 1 and then 2; a driver that + * collects the yields first and converts them afterwards sees the same + * object twice and records 2 twice. + */ + private class MutatingYieldOpDesc extends PythonOperatorDescriptor { + override def operatorInfo: OperatorInfo = + OperatorInfo( + userFriendlyName = "Mutating Yield", + operatorDescription = "yields one dict twice, changing it in between", + operatorGroupName = OperatorGroupConstants.UTILITY_GROUP, + inputPorts = List(InputPort()), + outputPorts = List(OutputPort()) + ) + + override def getOutputSchemas( + inputSchemas: Map[PortIdentity, Schema] + ): Map[PortIdentity, Schema] = + Map( + operatorInfo.outputPorts.head.id -> Schema().add(new Attribute("x", AttributeType.INTEGER)) + ) + + override def generatePythonCode(): String = + """from pytexera import * + | + |class ProcessTableOperator(UDFTableOperator): + | + | @overrides + | def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: + | row = {"x": 1} + | yield row + | row["x"] = 2 + | yield row + |""".stripMargin + } + + /** Reports the column names of the table it was handed, as one row. */ + private class TableColumnsOpDesc extends PythonOperatorDescriptor { + override def operatorInfo: OperatorInfo = + OperatorInfo( + userFriendlyName = "Table Columns", + operatorDescription = "yields the column names of its input table", + operatorGroupName = OperatorGroupConstants.UTILITY_GROUP, + inputPorts = List(InputPort()), + outputPorts = List(OutputPort()) + ) + + override def getOutputSchemas( + inputSchemas: Map[PortIdentity, Schema] + ): Map[PortIdentity, Schema] = + Map( + operatorInfo.outputPorts.head.id -> Schema().add( + new Attribute("columns", AttributeType.STRING) + ) + ) + + override def generatePythonCode(): String = + """from pytexera import * + | + |class ProcessTableOperator(UDFTableOperator): + | + | @overrides + | def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: + | yield {"columns": ",".join(table.columns)} + |""".stripMargin + } + + /** Reports the timestamp it was handed, as Python prints it. */ + private class TimestampTextOpDesc extends BinaryTypeOpDesc { + override def generatePythonCode(): String = + """from pytexera import * + | + |class ProcessTupleOperator(UDFOperatorV2): + | + | @overrides + | def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + | yield {"kind": str(tuple_["ts"])} + |""".stripMargin + } + + /** Declares one INTEGER column `x` and yields `row`, a Python dict literal. */ + private class YieldOpDesc(row: String) extends PythonOperatorDescriptor { + override def operatorInfo: OperatorInfo = + OperatorInfo( + userFriendlyName = "Yield", + operatorDescription = "yields one row as given", + operatorGroupName = OperatorGroupConstants.UTILITY_GROUP, + inputPorts = List(InputPort()), + outputPorts = List(OutputPort()) + ) + + override def getOutputSchemas( + inputSchemas: Map[PortIdentity, Schema] + ): Map[PortIdentity, Schema] = + Map( + operatorInfo.outputPorts.head.id -> Schema().add(new Attribute("x", AttributeType.INTEGER)) + ) + + override def generatePythonCode(): String = + s"""from pytexera import * + | + |class ProcessTupleOperator(UDFOperatorV2): + | + | @overrides + | def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + | yield $row + |""".stripMargin + } + + /** Reads a LARGE_BINARY column and writes out the reference it holds. + * + * The bytes of a large binary live in S3 and the field is the s3:// URI that + * points at them, so an operator can be handed one, and can hand one back, + * without any storage being reachable. + */ + private class LargeBinaryOpDesc(readsInput: Boolean) extends PythonOperatorDescriptor { + override def operatorInfo: OperatorInfo = + OperatorInfo( + userFriendlyName = "Large Binary", + operatorDescription = "reads or writes a reference to a large binary", + operatorGroupName = OperatorGroupConstants.UTILITY_GROUP, + inputPorts = List(InputPort()), + outputPorts = List(OutputPort()) + ) + + override def getOutputSchemas( + inputSchemas: Map[PortIdentity, Schema] + ): Map[PortIdentity, Schema] = + Map( + operatorInfo.outputPorts.head.id -> + (if (readsInput) Schema().add(new Attribute("uri", AttributeType.STRING)) + else Schema().add(new Attribute("blob", AttributeType.LARGE_BINARY))) + ) + + override def generatePythonCode(): String = + if (readsInput) + """from pytexera import * + | + |class ProcessTupleOperator(UDFOperatorV2): + | + | @overrides + | def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + | yield {"uri": tuple_["blob"].uri} + |""".stripMargin + else + """from pytexera import * + | + |class ProcessTupleOperator(UDFOperatorV2): + | + | @overrides + | def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + | yield {"blob": largebinary(tuple_["uri"])} + |""".stripMargin + } + + /** Reports the Python type of the BINARY cell it is handed. */ + private class BinaryTypeOpDesc extends PythonOperatorDescriptor { + override def operatorInfo: OperatorInfo = + OperatorInfo( + userFriendlyName = "Binary Type", + operatorDescription = "reports the type of a binary cell", + operatorGroupName = OperatorGroupConstants.UTILITY_GROUP, + inputPorts = List(InputPort()), + outputPorts = List(OutputPort()) + ) + + override def getOutputSchemas( + inputSchemas: Map[PortIdentity, Schema] + ): Map[PortIdentity, Schema] = + Map( + operatorInfo.outputPorts.head.id -> Schema().add( + new Attribute("kind", AttributeType.STRING) + ) + ) + + override def generatePythonCode(): String = + """from pytexera import * + | + |class ProcessTupleOperator(UDFOperatorV2): + | + | @overrides + | def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + | yield {"kind": type(tuple_["blob"]).__name__} + |""".stripMargin + } + + /** Calls predict on the BINARY cell it is handed, as a model's consumer does. */ + private class ModelPredictOpDesc extends BinaryTypeOpDesc { + override def generatePythonCode(): String = + """from pytexera import * + | + |class ProcessTupleOperator(UDFOperatorV2): + | + | @overrides + | def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + | yield {"kind": str(tuple_["blob"].predict([[1.0]])[0])} + |""".stripMargin + } + + // A fitted DecisionTreeClassifier behind the marker the cast writes, pickled + // by the interpreter the harness runs so the two share a sklearn. + private def fittedTreeCell(): Array[Byte] = { + val script = + """import base64, pickle, sys + |from sklearn.tree import DecisionTreeClassifier + |model = DecisionTreeClassifier(random_state=0).fit([[0.0], [1.0]], [0, 1]) + |sys.stdout.write(base64.b64encode(b"pickle " + pickle.dumps(model)).decode("ascii")) + |""".stripMargin + val encoded = Process(Seq(PyOpExecHarness.resolvePython(), "-c", script)).!! Review Comment: This model fixture fails on Windows with JDK 17 and Python 3.12. The quoted bytes literal is lost from the multiline command argument, and Python receives sys.stdout.write(base64.b64encode(bpickle followed by a SyntaxError. The same model creation and driver round trip pass in the direct Python probe. Please run this helper from a temporary Python file so the regression test reaches the harness on Windows too. -- 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]
