aglinxinyuan commented on code in PR #8671:
URL: https://github.com/apache/texera/pull/8671#discussion_r4501626667
##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/PythonOperatorDescriptor.scala:
##########
@@ -19,29 +19,224 @@
package org.apache.texera.amber.operator
+import com.fasterxml.jackson.annotation.JsonInclude.Include
+import com.fasterxml.jackson.core.JsonPointer
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.{ArrayNode, JsonNodeFactory,
ObjectNode}
import org.apache.texera.amber.core.executor.OpExecWithCode
+import org.apache.texera.amber.core.state.StateReferencing.{SIDECAR_PROPERTY,
textReferences}
import org.apache.texera.amber.core.tuple.Schema
import org.apache.texera.amber.core.virtualidentity.{ExecutionIdentity,
WorkflowIdentity}
import org.apache.texera.amber.core.workflow.{PhysicalOp, PortIdentity,
SchemaPropagationFunc}
+import org.apache.texera.amber.operator.PythonOperatorDescriptor._
+import org.apache.texera.amber.pybuilder.PythonLexerUtils.{
+ hasCommentOutsideQuotes,
+ hasUnclosedQuote,
+ isIdentChar,
+ updateTripleQuotedStringState
+}
+import
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.decoderExpression
+import org.apache.texera.amber.util.JSONUtils.objectMapper
+
+import scala.annotation.tailrec
+import scala.util.{Success, Try}
trait PythonOperatorDescriptor extends LogicalOp {
private def generatePythonCodeForRaisingException(ex: Throwable): String = {
s"#EXCEPTION DURING CODE GENERATION: ${ex.getMessage}"
}
+ /**
+ * `code` with every loop variable in `names`, each one that a String
property of this
+ * descriptor refers to, read from the iteration's state. The code is
generated before the loop
+ * runs, from the literal `$name` the property holds; pyb renders that text
as a decode
+ * expression the operator evaluates when it runs, which becomes
`loopVariableLookup(name)`
+ * instead.
+ */
+ private def withLoopVariableLookups(code: String, names: Iterable[String]):
String =
+ names.toSet.foldLeft(code) { (rewritten, name) =>
+ rewritten.replace(decoderExpression("$" + name),
loopVariableLookup(name))
+ }
+
+ /** This descriptor's code, rewritten by `rewrite`, or the code that says
why it failed. */
+ private def generatedCode(rewrite: String => String): String =
+ try {
+ rewrite(generatePythonCode())
+ } catch {
+ case ex: Throwable =>
+ // instead of throwing error directly, we embed the error in the code
+ // this can let upper-level compiler catch the error without
interrupting the schema propagation
+ generatePythonCodeForRaisingException(ex)
+ }
+
+ /**
+ * This descriptor's code with every loop variable its properties refer to
read from the
+ * iteration's state, and each numeric or boolean reference that the code
cannot read so: its
+ * pointer -> why. It generates the code anew on every call. Outside every
loop block the
+ * sidecar is empty, and the code is exactly the one `generatePythonCode`
returns. When no
+ * probe value generates the code, the code is why the generation failed,
for the compiler to
+ * report, and no reference is said to be unbound.
+ */
+ def loopVariableBinding: LoopVariableBinding = bindLoopVariables().binding
+
+ /**
+ * The binding, and the output schemas of the descriptor its code was
generated from.
+ *
+ * The code is generated before the loop runs, so a numeric or boolean
property's value is
+ * written into it, and the property holds a placeholder (0 / 0.0 / false)
there. To find where
+ * the value lands, the code is generated from copies of this descriptor:
the baseline sets each
+ * such reference to the first value of its probe pair, and one variant per
reference sets it to
+ * the second. Where the two codes differ by the two values as Python
writes them, and by
+ * nothing else, the baseline holds the value, and reads the variable
instead
+ * (`loopVariableValueLookup`), unless it lies in a text, a comment or a
name, or the descriptor
+ * checks or adjusts the value: a copy with an edge value or another probe
in its place must
+ * generate, holding that value in the very same places. When the
descriptor rejects a probe,
+ * the next pair is tried, for the other references' sake; when no baseline
generates, whether
+ * the failure is the values' cannot be told, and the code says why the
first one failed. The
+ * schema is the baseline's.
+ */
+ private def bindLoopVariables(): Bound =
+ if (stateReferences.isEmpty) {
+ Bound(LoopVariableBinding(generatedCode(identity), Map.empty),
getOutputSchemas)
+ } else {
+ val tree = copyMapper.valueToTree[ObjectNode](this)
+ tree.remove(SIDECAR_PROPERTY) // so that a copy refers to no loop
variable
+ val text = textReferences(tree, stateReferences)
+ val typed = stateReferences -- text.keys
+ val kinds = typed.flatMap { case (pointer, _) =>
kindOf(tree.at(pointer)).map(pointer -> _) }
+ val unknown = (typed -- kinds.keys).map { case (pointer, _) => pointer
-> generatedFromValue }
+ val textLookups = withLoopVariableLookups(_: String, text.values)
+ if (kinds.isEmpty) {
+ Bound(LoopVariableBinding(generatedCode(textLookups), unknown),
getOutputSchemas)
+ } else {
+ probing(tree, kinds).fold(
+ failure =>
+ Bound(
+
LoopVariableBinding(generatePythonCodeForRaisingException(failure), unknown),
Review Comment:
Moved to #9359 with the rest of the number and true/false references, where
it's fixed: when no probe value generates the code, the probing starts from the
operator's own defaults (Row Height 30) and the probe values it rejects count
as values it checks, so Row Height gets `it checks or adjusts the value before
the loop runs`, as Font Size does. On this PR a `$h` Row Height is reported
ahead of the code-generation failure, with `numeric and boolean properties are
written into its generated code before the loop runs` (8aa187c259).
##########
amber/src/main/python/core/models/operator.py:
##########
@@ -90,8 +100,124 @@ def _get_template_decoder(self) ->
"Operator.PythonTemplateDecoder":
def decode_python_template(self, data: Union[str, bytes]) -> str:
return self._get_template_decoder().decode(data)
+ def loop_variable_text(self, name: str) -> str:
+ """
+ The text of loop variable ``name`` in the state messages handed to this
+ operator, the latest one that carried it winning. Inside a control
+ block, the code generated for an operator calls this where a text
+ property holds ``$name``, in place of decoding the literal, so the
+ value is read when the code runs. It is spelled as a JVM operator's
+ text property binds it (``StateReferenceBinding``): a boolean as
``true``
+ or ``false``, and only a scalar at all.
+
+ :param name: str, the loop variable's name, without the leading ``$``.
+ :return: str, the variable's value, as text.
+ """
+ if self._loop_variables is None:
+ raise RuntimeError(
+ f"loop variable ${name} is read before the iteration's state
arrived"
+ )
+ if name not in self._loop_variables:
+ raise RuntimeError(
+ f"the operator refers to loop variable ${name}, "
+ "but no state message carried it"
+ )
+ value = self._loop_variables[name]
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, (str, int, float)):
+ return str(value)
+ raise RuntimeError(
+ f"the operator refers to loop variable ${name}, "
+ f"but its value {value!r} is not a scalar"
+ )
+
+ def loop_variable_value(self, name: str, kind: str) -> Union[int, float,
bool]:
+ """
+ The value of loop variable ``name``, its text (``loop_variable_text``)
+ converted to ``kind``. Inside a control block, the code generated for
+ an operator calls this where a numeric or boolean property holds
+ ``$name``, in place of the value written into the code, so the value is
+ read when the code runs. It is converted as a JVM operator's numeric or
+ boolean property binds it (``StateReferenceBinding``), from its text:
an
+ integer must be integral and fit a signed 64-bit long, a number is any
+ numeral, and a boolean is ``true`` or ``false`` in any case, never
``1``
+ or ``0``.
+
+ :param name: str, the loop variable's name, without the leading ``$``.
+ :param kind: str, ``integer``, ``number`` or ``boolean``: the JSON type
+ of the property that holds ``$name``.
+ :return: int, float or bool, the variable's value as ``kind``.
+ """
+ if kind not in ("integer", "number", "boolean"):
+ raise ValueError(
+ f"loop variable ${name} cannot be read as {kind!r}: "
+ "the kind is one of 'integer', 'number' and 'boolean'"
+ )
+ text = self.loop_variable_text(name).strip()
+ value = self._loop_variables[name]
+
+ def not_a(description: str) -> RuntimeError:
+ return RuntimeError(
+ f"the operator refers to loop variable ${name}, "
+ f"but its value {value!r} is not {description}"
+ )
+
+ if kind == "boolean":
+ if text.lower() not in ("true", "false"):
+ raise not_a("a boolean")
+ return text.lower() == "true"
+ description = "a number" if kind == "number" else "an integer"
+ try:
+ numeral = Decimal(text)
+ except InvalidOperation:
+ raise not_a(description) from None
+ if kind == "number":
+ try:
+ return float(numeral)
+ except ValueError: # a signalling NaN
+ raise not_a(description) from None
+ # BigDecimal.longValueExact: integral and within a signed 64-bit long.
+ if (
+ not numeral.is_finite()
+ or numeral != numeral.to_integral_value()
+ or not -(2**63) <= numeral < 2**63
+ ):
+ raise not_a(description)
+ return int(numeral)
+
+ def register_state(self, state: State) -> None:
+ """
+ Register ``state`` as the latest state message handed to this operator.
+ It becomes ``self.state``, and its values join the loop variables
+ ``loop_variable_text`` and ``loop_variable_value`` read, replacing
+ those of the same name. The runtime calls this right before
+ ``process_state``.
+
+ :param state: State, the state message that arrived.
+ """
+ self.state = state
+ self._loop_variables = {**(self._loop_variables or {}), **state}
Review Comment:
Yes — `loop_variable_text` now reads #8642's `loop_variables`, where the
smallest nesting depth wins, so your outer/inner/outer order reads 5, as on the
JVM (merged in 014c261df7, pinned by fb2ddbd353). The generated code also fixes
the values right before the operator's first tuple, as `bindStateReferences`
does (1d28ad146d), and fails there for a referenced variable no state carried
(d083d99ac8), so a later state no longer changes the `i` it reads.
##########
common/workflow-compiler/src/main/scala/org/apache/texera/common/compiler/WorkflowCompiler.scala:
##########
@@ -166,20 +170,101 @@ object WorkflowCompiler {
* A reference is bound in the executor that `ExecFactory` builds from the
descriptor's JSON: the
* state message writes the loop variable into the descriptor that executor
parsed. An operator
* whose executor runs code instead -- a UDF, or a descriptor that
generates Python from its
- * properties, such as the sklearn operators -- never takes that path: its
code is built from the
- * placeholders before the loop runs, and nothing binds them.
+ * properties, such as the sklearn operators -- never takes that path: its
code is built before
+ * the loop runs. A UDF's code and properties are the user's, and
+ * nothing binds them. A numeric or boolean property's value is read from
the loop state where
+ * the descriptor finds it written into its code, and
`PythonOperatorDescriptor`'s
+ * `loopVariableBinding` says why when it cannot be. A String property's
`$name` is bound only
+ * where pyb's decoder rendered it, which
+ * `PythonOperatorDescriptor` turned into a read of the loop state,
`loopVariableLookup(name)`,
+ * and then only if the code holds the text `$name` nowhere (where it does,
the code pastes it
+ * in as it is) and no output column the operator adds holds the text (its
schema is computed
+ * from the literal). A lookup the code runs before the iteration's state
arrives, such as one
+ * in `open`, fails when it runs, with a message that says so. The texts
are judged once every
+ * numeric or boolean reference is bound: until then the code holds a probe
value in its place,
+ * which may decide what the code reads.
+ * When the generation failed (with every probe value, where a numeric or
boolean property
+ * refers to a loop variable) there is no code to read either way, and the
code-generation
+ * check reports why it failed instead.
+ *
+ * @param physicalOps the operator's own physical operators, their schemas
propagated.
*/
- def unbindableStateReferences(logicalOp: LogicalOp, subPlan: PhysicalPlan):
Option[Throwable] =
- Option.when(
- logicalOp.stateReferences.nonEmpty &&
- subPlan.operators.exists(_.opExecInitInfo.isInstanceOf[OpExecWithCode])
- ) {
- new UnsupportedOperationException(
- s"${logicalOp.operatorInfo.userFriendlyName} cannot refer to loop
variables yet " +
- s"(${formatReferences(logicalOp.stateReferences)}): its code is
generated before " +
- "the loop runs"
- )
+ def unbindableStateReferences(
+ logicalOp: LogicalOp,
+ physicalOps: Iterable[PhysicalOp]
+ ): Option[Throwable] = {
+ val codes = physicalOps.toSeq.map(_.opExecInitInfo).collect {
+ case OpExecWithCode(code, language) => (code, language)
}
+ if (logicalOp.stateReferences.isEmpty || codes.isEmpty) {
+ None
+ } else {
+ val unbound: Seq[(Iterable[String], String)] = logicalOp match {
+ case generator: PythonOperatorDescriptor if codes.forall(_._2 ==
"python") =>
+ val tree = objectMapper.valueToTree[ObjectNode](logicalOp)
+ val text = textReferences(tree, logicalOp.stateReferences)
+ val scripts = codes.map(_._1)
+ val added = addedColumns(physicalOps)
+ def whyUnbound(name: String): Option[String] = {
+ val lookup = loopVariableLookup(name)
+ if (scripts.exists(_.contains("$" + name))) Some(pastedIntoCode)
+ else if (!scripts.exists(_.contains(lookup))) Some(unreadByCode)
+ else if (added.exists(_.contains("$" + name)))
Some(namesOutputColumn)
+ else None
+ }
+ val typedUnbound = generator.loopVariableBinding.unbound
Review Comment:
On this PR `WorkflowCompiler.unbindableStateReferences` is that one place:
it decides every reason from the code the operator generates once for its
physical plan (8aa187c259), now including a read the code would run in `open`
(8f83171e59). #9359 probes the descriptor once per compile and decides its
number and true/false reasons in the same place as the text ones.
--
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]