kunwp1 commented on code in PR #9515:
URL: https://github.com/apache/texera/pull/9515#discussion_r4596366898
##########
common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/Schema.scala:
##########
@@ -108,12 +109,15 @@ case class Schema @JsonCreator() (
list + (attr.getName -> attr.getType.name())
)
+ private def lowerCaseAttributeNames: Set[String] =
+ attributes.iterator.map(_.getName.toLowerCase).toSet
Review Comment:
`attributeIndex` (line 39) is already keyed by the lowercase name, so
`attributeIndex.keySet` is this set without rebuilding it. `remove` at line 178
also inlines the same expression instead of calling the helper. Using
`attributeIndex.keySet` in both places lets the helper go.
##########
common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/Schema.scala:
##########
@@ -28,6 +28,7 @@ import scala.collection.immutable.ListMap
* Represents the schema of a tuple, consisting of a list of attributes.
* The schema is immutable, and any modifications result in a new Schema
instance.
*/
+@SerialVersionUID(-8380542583803575822L)
Review Comment:
These pins (here, on `Tuple`, `Tuple.Builder` and
`MachineLearningScorerOpDesc`) don't protect anything today. `cluster.conf`
sets `allow-java-serialization = off` and routes `Serializable` through Kryo,
which ignores `serialVersionUID`, and nothing in the repo writes these classes
with `ObjectOutputStream`. I'd drop them, or say in the PR what they're meant
to keep compatible.
##########
common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/Tuple.scala:
##########
@@ -215,9 +234,12 @@ object Tuple {
def addSequentially(fields: Array[Any]): Builder = {
require(fields != null, "Fields cannot be null")
checkSchemaMatchesFields(schema.getAttributes, fields)
- schema.getAttributes.zip(fields).foreach {
- case (attribute, field) =>
- this.add(attribute, field)
+ val attributes = schema.getAttributes.iterator
+ val values = fields.clone()
+ var index = 0
+ while (attributes.hasNext && index < values.length) {
+ this.add(attributes.next(), values(index))
Review Comment:
`fields.clone()` adds a copy per call, and `ArrowUtils.getTexeraTuple`
already hands in a fresh array. `checkSchemaMatchesFields` has just matched the
two lengths, so `index < values.length` can go too: `fields.foreach(field =>
this.add(attributes.next(), field))`. The same applies to `getFields.clone()`
in `SeqTupleLike.enforceSchema`.
##########
common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/Tuple.scala:
##########
@@ -171,20 +189,21 @@ object Tuple {
/**
* Builder class for constructing Tuple instances in a flexible and
controlled manner.
*/
+ @SerialVersionUID(-699268362870086216L)
case class Builder(schema: Schema) {
private val fieldNameMap = mutable.Map.empty[String, Any]
def add(tuple: Tuple, isStrictSchemaMatch: Boolean = true): Builder = {
require(tuple != null, "Tuple cannot be null")
- tuple.getFields.zipWithIndex.foreach {
- case (field, i) =>
- val attribute = tuple.schema.getAttributes(i)
- if (!isStrictSchemaMatch &&
!schema.containsAttribute(attribute.getName)) {
- // Skip if not matching in non-strict mode
- } else {
- add(attribute, tuple.getFields(i))
- }
+ val fieldCount = tuple.getFields.length
+ var index = 0
+ while (index < fieldCount) {
+ val attribute = tuple.schema.getAttributes(index)
+ if (isStrictSchemaMatch ||
schema.containsAttribute(attribute.getName)) {
+ this.add(attribute, tuple.getFields(index))
Review Comment:
`getAttributes` is a `List`, so `getAttributes(index)` walks from the head
each time and this loop is still O(n²) per tuple. One iterator over the
attributes does it in one pass, like the other loops here:
```scala
val attributes = tuple.schema.getAttributes.iterator
tuple.getFields.foreach { field =>
val attribute = attributes.next()
if (isStrictSchemaMatch ||
schema.containsAttribute(attribute.getName)) {
this.add(attribute, field)
}
}
```
##########
common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/Tuple.scala:
##########
@@ -83,25 +84,44 @@ case class Tuple @JsonCreator() (
this
}
- override def hashCode: Int =
util.Arrays.deepHashCode(getFields.map(_.asInstanceOf[AnyRef]))
+ override def hashCode: Int =
+ util.Arrays.deepHashCode(getFields.clone().asInstanceOf[Array[AnyRef]])
override def equals(obj: Any): Boolean =
obj match {
- case that: Tuple =>
- this.schema == that.schema &&
- this.getFields.zip(that.getFields).forall {
- case (field1: Array[Byte], field2: Array[Byte]) =>
- field1.sameElements(field2) // for Binary, use sameElements
instead of == to compare
- case (field1, field2) =>
- field1 == field2
- }
+ case that: Tuple if this.schema == that.schema =>
+ val leftFields = this.getFields
+ val rightFields = that.getFields
+ val fieldCount = math.min(leftFields.length, rightFields.length)
+ // Capture field references before any user-defined equals can change
either tuple.
+ val leftSnapshot =
util.Arrays.copyOf(leftFields.asInstanceOf[Array[AnyRef]], fieldCount)
+ val rightSnapshot =
util.Arrays.copyOf(rightFields.asInstanceOf[Array[AnyRef]], fieldCount)
+ var index = 0
+ var equal = true
+ while (index < fieldCount && equal) {
+ val left = leftSnapshot(index)
+ val right = rightSnapshot(index)
+ equal =
+ if (left.isInstanceOf[Array[Byte]] &&
right.isInstanceOf[Array[Byte]])
+ util.Arrays.equals(left.asInstanceOf[Array[Byte]],
right.asInstanceOf[Array[Byte]])
+ else
+ left == right
+ index += 1
+ }
+ equal
Review Comment:
Distinct and the set operators key `HashSet`s by `Tuple`, so these run per
row. The `clone()` and the two `copyOf` snapshots are new array copies, which
is what the PR sets out to remove. `Array[Any]` is already an `Object[]` at
runtime, so neither method needs a copy:
```scala
override def hashCode: Int =
util.Arrays.deepHashCode(getFields.asInstanceOf[Array[AnyRef]])
override def equals(obj: Any): Boolean =
obj match {
case that: Tuple if this.schema == that.schema =>
val left = this.getFields
val right = that.getFields
(0 until math.min(left.length, right.length)).forall(i =>
fieldEquals(left(i), right(i)))
case _ => false
}
private def fieldEquals(left: Any, right: Any): Boolean =
(left, right) match {
case (l: Array[Byte], r: Array[Byte]) => util.Arrays.equals(l, r)
case _ => left == right
}
```
##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/machineLearning/Scorer/MachineLearningScorerOpDesc.scala:
##########
@@ -134,34 +142,36 @@ class MachineLearningScorerOpDesc extends
PythonOperatorDescriptor with Standalo
* classification target even though a continuous one is not, and the schema
* cannot tell the two apart.
*/
+ private def requireScoredColumn(
Review Comment:
This lands between the scaladoc above and `validateScoredColumns`, so that
doc now attaches to the helper. Moving the helper below `validateScoredColumns`
keeps it on the right method.
##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/machineLearning/Scorer/MachineLearningScorerOpDesc.scala:
##########
@@ -194,21 +207,23 @@ class MachineLearningScorerOpDesc extends
PythonOperatorDescriptor with Standalo
inputSchemas: Map[PortIdentity, Schema]
): Map[PortIdentity, Schema] = {
validateScoredColumns(inputSchemas)
- val metrics = if (isRegression) {
- regressionMetrics.map(_.getName())
- } else {
- classificationMetrics.map(_.getName())
- }
- val baseSchema = if (!isRegression) {
- Schema(List(new Attribute("Class", AttributeType.STRING)))
- } else {
- Schema(List())
+ val metricNames =
+ if (isRegression) regressionMetrics.map(_.getName())
+ else classificationMetrics.map(_.getName())
+ val builder = List.newBuilder[Attribute]
+ val seenNames = mutable.HashSet.empty[String]
+ if (!isRegression) {
+ seenNames += "class"
+ builder += new Attribute("Class", AttributeType.STRING)
}
-
- val outputSchema = metrics.foldLeft(baseSchema) { (currentSchema,
metricName) =>
- currentSchema.add(new Attribute(metricName, AttributeType.DOUBLE))
+ metricNames.foreach { metricName =>
+ if (!seenNames.add(metricName.toLowerCase)) {
+ throw new RuntimeException(s"Attribute name '$metricName' already
exists in the schema")
Review Comment:
This copies `Schema.add`'s duplicate check and its message, and the
hard-coded `"class"` has to track the attribute name above. It runs once per
compile on a handful of metrics, so the old fold keeps the rule in one place:
```scala
val baseSchema =
if (isRegression) Schema() else Schema(List(new Attribute("Class",
AttributeType.STRING)))
val outputSchema = metricNames.foldLeft(baseSchema) { (schema,
metricName) =>
schema.add(new Attribute(metricName, AttributeType.DOUBLE))
}
```
##########
common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/udf/java/JavaUdfUiParameterInjectorSpec.scala:
##########
@@ -226,6 +226,18 @@ class JavaUdfUiParameterInjectorSpec extends AnyFlatSpec
with Matchers {
executor.close()
}
}
+
+ it should "preserve unicode and mixed line endings while rejecting
uninitialized or multi-field injections" in {
Review Comment:
The title says this rejects uninitialized and multi-field injections, but
the body only checks line endings and the value. The multi-declarator refusal
is already covered by `int value, another;` in the loop at line 157, so maybe
drop that half of the name.
##########
common/workflow-core/src/main/scala/org/apache/texera/amber/util/ArrowUtils.scala:
##########
@@ -74,37 +74,43 @@ object ArrowUtils extends LazyLogging {
val arrowSchema = vectorSchemaRoot.getSchema
val schema = toTexeraSchema(arrowSchema)
- Tuple
- .builder(schema)
- .addSequentially(
- vectorSchemaRoot.getFieldVectors.asScala.zipWithIndex.map {
- case (fieldVector: FieldVector, index: Int) =>
- val value: AnyRef = fieldVector.getObject(rowIndex)
- try {
- // Use the attribute type from the schema (which includes
metadata)
- // instead of deriving it from the Arrow type
- val attributeType = schema.getAttributes(index).getType
- // A timestamp and an unsigned integer are the types whose field
- // says more than the schema does, so they are the only ones that
- // read the field: an unsigned column arrives as INTEGER or LONG.
- attributeType match {
- case AttributeType.TIMESTAMP => wallClockOf(value,
fieldVector.getField.getType)
- case AttributeType.INTEGER | AttributeType.LONG =>
- AttributeTypeUtils.parseField(
- unsignedValueOf(value, fieldVector.getField.getType),
- attributeType
- )
- case _ => AttributeTypeUtils.parseField(value, attributeType)
- }
- } catch {
- case e: Exception =>
- logger.warn("Caught error during parsing Arrow value back to
Texera value", e)
- null
- }
-
- }.toArray
- )
- .build()
+ val fieldVectors = vectorSchemaRoot.getFieldVectors
+ val fieldValues = new Array[Any](fieldVectors.size())
+ val vectors = fieldVectors.iterator()
+ val attributes = schema.getAttributes.iterator
+ var index = 0
+ while (vectors.hasNext) {
+ val fieldVector = vectors.next()
+ val value: AnyRef = fieldVector.getObject(rowIndex)
+ val fieldValue =
+ try {
+ // Use the attribute type from the schema (which includes metadata)
+ // instead of deriving it from the Arrow type. Preserve the indexed
+ // lookup's error when the vector list is wider than the schema.
+ val attribute = if (attributes.hasNext) attributes.next() else
schema.getAttributes(index)
Review Comment:
`schema` comes from this root's own Arrow schema, so there is one attribute
per vector and the `schema.getAttributes(index)` fallback can't run.
`attributes.next().getType` is enough.
Separately, and not new here: line 75 rebuilds the Texera schema for every
row, which likely costs more than this loop saves. Converting it once per
`VectorSchemaRoot` would be a good follow-up.
##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/machineLearning/Scorer/MachineLearningScorerOpDesc.scala:
##########
@@ -174,12 +184,15 @@ class MachineLearningScorerOpDesc extends
PythonOperatorDescriptor with Standalo
// A matching pair can still be one sklearn refuses as labels. Bytes
fail
// every metric. Timestamps only fail the per-class ones, since
Accuracy
// just counts equal rows.
- val perClass = classificationMetrics.filterNot(_ ==
classificationMetricsFnc.accuracy)
+ // Keep validation of a null metrics list ahead of schema construction.
+ val perClass =
+ if (classificationMetrics == null || actualType ==
AttributeType.TIMESTAMP)
Review Comment:
`classificationMetrics == null ||` is only there to dereference null and
throw, which reads like a bug. A null list still throws an NPE from
`classificationMetrics.map` in `getOutputSchemas`, so the earlier shape keeps
the new spec passing:
```scala
val refusedBy =
if (actualType == AttributeType.BINARY || actualType ==
AttributeType.LARGE_BINARY)
classificationMetrics
else if (actualType == AttributeType.TIMESTAMP)
classificationMetrics.filterNot(_ ==
classificationMetricsFnc.accuracy)
else Nil
```
--
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]