From 06e374145cf11f188248e6fe646676000a3bae71 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:43:17 -0800 Subject: [PATCH 01/15] Optimize Schema metadata, Row storage, RowWithGetters caching, and RowMessages Eliminates steady-state allocations and hash lookups across core schema model types: - Schema: singleton Options.none(), switch-based TypeName predicates, O(1) nameOf/getFieldNames, fast equals/equivalent, and safely published SchemaMetadata bitmasks with POPCNT (<64) and lazy highContainerCacheSlots (>=64) compact container slot lookup. - Row / RowWithStorage: internal zero-copy Row.attachValues(Schema, Object[]) and Row.withFieldValueGetters factories, direct Object[] backing in RowWithStorage, single-alloc getDateTime, fast getBaseValues, and reference-identity deepEquals / logical-type deepHashCode fix. - RowWithGetters: compact lazy container cache array replacing TreeMap + per-call anonymous Function, pre-resolved getter constructor, and hashCode parity with RowWithStorage. - FieldAccessDescriptor / RowMessages / SchemaUtils: cached singleton descriptors, fast schema-identity check and pre-sized buffers in RowToBytesFn, and shared path/identity helpers. --- .../sdk/schemas/FieldAccessDescriptor.java | 25 +- .../apache/beam/sdk/schemas/RowMessages.java | 16 +- .../org/apache/beam/sdk/schemas/Schema.java | 467 ++++++++++++++---- .../apache/beam/sdk/schemas/SchemaUtils.java | 130 ++++- .../java/org/apache/beam/sdk/values/Row.java | 311 ++++++++---- .../beam/sdk/values/RowWithGetters.java | 88 ++-- .../beam/sdk/values/RowWithStorage.java | 63 ++- .../apache/beam/sdk/schemas/SchemaTest.java | 9 +- 8 files changed, 829 insertions(+), 280 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FieldAccessDescriptor.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FieldAccessDescriptor.java index 4dec9581e027..eca1883ce206 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FieldAccessDescriptor.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FieldAccessDescriptor.java @@ -90,12 +90,21 @@ public enum Kind { public abstract MapQualifier getMap(); + private static final Qualifier LIST_ALL = + AutoOneOf_FieldAccessDescriptor_FieldDescriptor_Qualifier.list(ListQualifier.ALL); + private static final Qualifier MAP_ALL = + AutoOneOf_FieldAccessDescriptor_FieldDescriptor_Qualifier.map(MapQualifier.ALL); + public static Qualifier of(ListQualifier qualifier) { - return AutoOneOf_FieldAccessDescriptor_FieldDescriptor_Qualifier.list(qualifier); + return qualifier == ListQualifier.ALL + ? LIST_ALL + : AutoOneOf_FieldAccessDescriptor_FieldDescriptor_Qualifier.list(qualifier); } public static Qualifier of(MapQualifier qualifier) { - return AutoOneOf_FieldAccessDescriptor_FieldDescriptor_Qualifier.map(qualifier); + return qualifier == MapQualifier.ALL + ? MAP_ALL + : AutoOneOf_FieldAccessDescriptor_FieldDescriptor_Qualifier.map(qualifier); } } @@ -157,9 +166,12 @@ static Builder builder() { .setNestedFieldsAccessed(Collections.emptyMap()); } + private static final FieldAccessDescriptor EMPTY = builder().build(); + private static final FieldAccessDescriptor ALL_FIELDS = builder().setAllFields(true).build(); + // Return a descriptor that accesses all fields in a row. public static FieldAccessDescriptor withAllFields() { - return builder().setAllFields(true).build(); + return ALL_FIELDS; } /** @@ -359,7 +371,7 @@ public static FieldAccessDescriptor union( /** Return an empty {@link FieldAccessDescriptor}. */ public static FieldAccessDescriptor create() { - return builder().build(); + return EMPTY; } /** @@ -570,6 +582,11 @@ private FieldDescriptor fillInMissingQualifiers(FieldDescriptor fieldDescriptor, // simple case where they are all wildcards. For example, if a is a list of a list of row, // the user could select a[*][*].b, however we allow them to simply type a.b for brevity. FieldType fieldType = schema.getField(fieldDescriptor.getFieldId()).getType(); + if (!fieldType.getTypeName().isCollectionType() && !fieldType.getTypeName().isMapType()) { + return fieldDescriptor.getQualifiers().isEmpty() + ? fieldDescriptor + : fieldDescriptor.toBuilder().setQualifiers(Collections.emptyList()).build(); + } Iterator qualifierIt = fieldDescriptor.getQualifiers().iterator(); List qualifiers = Lists.newArrayList(); while (fieldType.getTypeName().isCollectionType() || fieldType.getTypeName().isMapType()) { diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/RowMessages.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/RowMessages.java index af2ff7cedbdf..9acb393ffebf 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/RowMessages.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/RowMessages.java @@ -29,6 +29,7 @@ import org.apache.beam.sdk.transforms.SimpleFunction; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptor; +import org.checkerframework.checker.nullness.qual.Nullable; @Internal public final class RowMessages { @@ -90,7 +91,7 @@ public static SimpleFunction rowToBytesFn( } private static byte[] toBytes(Coder coder, T message) throws IOException { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final ByteArrayOutputStream out = new ByteArrayOutputStream(128); coder.encode(message, out); return out.toByteArray(); } @@ -112,7 +113,8 @@ private RowToBytesFn( @Override public byte[] apply(Row row) { - if (!schema.equivalent(row.getSchema())) { + Schema rowSchema = row.getSchema(); + if (!schema.equals(rowSchema) && !schema.equivalent(rowSchema)) { row = switchFieldsOrder(row); } final T message = fromRowFn.apply(row); @@ -124,9 +126,13 @@ public byte[] apply(Row row) { } private Row switchFieldsOrder(Row row) { - Row.Builder convertedRow = Row.withSchema(schema); - schema.getFields().forEach(field -> convertedRow.addValue(row.getValue(field.getName()))); - return convertedRow.build(); + Schema rowSchema = row.getSchema(); + int count = schema.getFieldCount(); + @Nullable Object[] values = new @Nullable Object[count]; + for (int i = 0; i < count; i++) { + values[i] = row.getValue(rowSchema.indexOf(schema.getField(i).getName())); + } + return Row.withSchema(schema).addValues(java.util.Arrays.asList(values)).build(); } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/Schema.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/Schema.java index 5d7819d9f070..0b666784986c 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/Schema.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/Schema.java @@ -36,6 +36,7 @@ import java.util.stream.Collector; import java.util.stream.Collectors; import javax.annotation.concurrent.Immutable; +import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.values.Row; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.CaseFormat; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; @@ -111,6 +112,144 @@ public String toString() { private final Options options; + // Lazy transient immutable metadata holder derived solely from immutable fields/options. + // Published via a single volatile reference so concurrent post-deserialization init has zero + // data races under JLS ยง17.4.5. + private static final int FLAG_HAS_NULLABLE_FIELDS = 1; + private static final int FLAG_HAS_LOGICAL_TYPES = 1 << 1; + private static final int FLAG_STATIC_ENCODING = 1 << 2; + private static final String OPTION_STATIC_ENCODING = "beam:option:row:static_encoding"; + + private static final class SchemaMetadata { + final int flags; + final long nullableFieldMask; + final long cacheableContainerMask; + final int cacheableContainerCount; + // Compact cache slots for fields >= 64; null unless a container field exists at index >= 64. + final int @Nullable [] highContainerCacheSlots; + + SchemaMetadata( + int flags, + long nullableFieldMask, + long cacheableContainerMask, + int cacheableContainerCount, + int @Nullable [] highContainerCacheSlots) { + this.flags = flags; + this.nullableFieldMask = nullableFieldMask; + this.cacheableContainerMask = cacheableContainerMask; + this.cacheableContainerCount = cacheableContainerCount; + this.highContainerCacheSlots = highContainerCacheSlots; + } + } + + private transient volatile @Nullable SchemaMetadata metadata; + private transient volatile @Nullable List<@NonNull String> cachedFieldNames; + + private SchemaMetadata ensureMetadata() { + SchemaMetadata md = metadata; + if (md != null) { + return md; + } + int computed = 0; + long nullableMask = 0L; + long cacheableMask = 0L; + int containerCount = 0; + int @Nullable [] highContainerSlots = null; + List localFields = this.fields; + int count = localFields.size(); + for (int i = 0; i < count; i++) { + FieldType type = localFields.get(i).getType(); + if (type.getNullable()) { + computed |= FLAG_HAS_NULLABLE_FIELDS; + if (i < 64) { + nullableMask |= (1L << i); + } + } + TypeName tn = type.getTypeName(); + if (tn == TypeName.LOGICAL_TYPE) { + computed |= FLAG_HAS_LOGICAL_TYPES; + } else if (tn == TypeName.MAP || tn == TypeName.ARRAY || tn == TypeName.ITERABLE) { + if (i < 64) { + cacheableMask |= (1L << i); + } else { + if (highContainerSlots == null) { + highContainerSlots = new int[count - 64]; + Arrays.fill(highContainerSlots, -1); + } + highContainerSlots[i - 64] = containerCount; + } + containerCount++; + } + } + if (options.hasOptions() + && Boolean.TRUE.equals(options.getValueOrDefault(OPTION_STATIC_ENCODING, false))) { + computed |= FLAG_STATIC_ENCODING; + } + md = + new SchemaMetadata( + computed, nullableMask, cacheableMask, containerCount, highContainerSlots); + this.metadata = md; + return md; + } + + /** Returns whether any top-level field of this schema is nullable. */ + @Internal + public boolean hasNullableFields() { + return (ensureMetadata().flags & FLAG_HAS_NULLABLE_FIELDS) != 0; + } + + /** Returns whether any top-level field of this schema is a {@link TypeName#LOGICAL_TYPE}. */ + @Internal + public boolean hasLogicalTypes() { + return (ensureMetadata().flags & FLAG_HAS_LOGICAL_TYPES) != 0; + } + + /** Returns whether this schema has static encoding enabled. */ + @Internal + public boolean isStaticEncoding() { + return (ensureMetadata().flags & FLAG_STATIC_ENCODING) != 0; + } + + /** + * Returns whether field {@code index} is nullable, using an O(1) bitmask for {@code index < 64}. + */ + @Internal + public boolean isFieldNullable(int index) { + SchemaMetadata md = ensureMetadata(); + if (index >= 0 && index < 64 && index < fields.size()) { + return (md.nullableFieldMask & (1L << index)) != 0L; + } + return fields.get(index).getType().getNullable(); + } + + /** + * Returns the compact cache slot index {@code [0, getCacheableContainerCount())} if field {@code + * index} is a cacheable container type (ARRAY, ITERABLE, or MAP), or {@code -1} otherwise. + * + *

For {@code index < 64}, computes the slot directly from the 64-bit bitmask via {@link + * Long#bitCount} with zero array allocation or indirection. + */ + @Internal + public int getContainerCacheSlot(int index) { + if (index < 0 || index >= fields.size()) { + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + fields.size()); + } + SchemaMetadata md = ensureMetadata(); + if (index < 64) { + long mask = md.cacheableContainerMask; + long bit = 1L << index; + return (mask & bit) == 0L ? -1 : Long.bitCount(mask & (bit - 1L)); + } + int @Nullable [] highSlots = md.highContainerCacheSlots; + return highSlots == null ? -1 : highSlots[index - 64]; + } + + /** Returns the number of top-level cacheable container fields (ARRAY, ITERABLE, or MAP). */ + @Internal + public int getCacheableContainerCount() { + return ensureMetadata().cacheableContainerCount; + } + /** Builder class for building {@link Schema} objects. */ public static class Builder { List fields; @@ -334,6 +473,7 @@ public Schema(List fields, Options options) { this.options = options; this.hashCode = Objects.hash(this.fieldIndices, this.fields, this.options); this.uuid = UUID.randomUUID(); + ensureMetadata(); } public static Schema of(Field... fields) { @@ -420,24 +560,34 @@ public boolean equals(@Nullable Object o) { if (this.hashCode != other.hashCode) { return false; } - return Objects.equals(fieldIndices, other.fieldIndices) - && Objects.equals(getFields(), other.getFields()) - && Objects.equals(getOptions(), other.getOptions()); + // Same ordered fields strictly implies same fieldIndices (built solely from fields in ctor). + int count = this.fields.size(); + if (count != other.fields.size()) { + return false; + } + for (int i = 0; i < count; i++) { + if (!this.fields.get(i).equals(other.fields.get(i))) { + return false; + } + } + return Objects.equals(this.options, other.options); } /** Returns true if two schemas are equal ignoring field names and descriptions. */ + @SuppressWarnings("ReferenceEquality") public boolean typesEqual(Schema other) { - if (uuid != null && other.uuid != null && Objects.equals(uuid, other.uuid)) { + if (this == other) { return true; } - if (getFieldCount() != other.getFieldCount()) { - return false; + if (uuid != null && other.uuid != null && Objects.equals(uuid, other.uuid)) { + return true; } - if (!Objects.equals(fieldIndices.values(), other.fieldIndices.values())) { + int count = getFieldCount(); + if (count != other.getFieldCount()) { return false; } - for (int i = 0; i < getFieldCount(); ++i) { - if (!getField(i).typesEqual(other.getField(i))) { + for (int i = 0; i < count; ++i) { + if (!fields.get(i).typesEqual(other.fields.get(i))) { return false; } } @@ -466,24 +616,42 @@ public boolean assignableToIgnoreNullable(Schema other) { return equivalent(other, EquivalenceNullablePolicy.IGNORE); } + @SuppressWarnings("ReferenceEquality") private boolean equivalent(Schema other, EquivalenceNullablePolicy nullablePolicy) { - if (other.getFieldCount() != getFieldCount()) { + if (this == other) { + return true; + } + if (uuid != null && other.uuid != null && uuid.equals(other.uuid)) { + return true; + } + int count = fields.size(); + if (other.fields.size() != count) { return false; } - List otherFields = - other.getFields().stream() - .sorted(Comparator.comparing(Field::getName)) - .collect(Collectors.toList()); - List actualFields = - getFields().stream() - .sorted(Comparator.comparing(Field::getName)) - .collect(Collectors.toList()); - - for (int i = 0; i < otherFields.size(); ++i) { - Field otherField = otherFields.get(i); - Field actualField = actualFields.get(i); - if (!actualField.equivalent(otherField, nullablePolicy)) { + // Fast path: fields in matching order (zero allocations). + // Falls back to O(1) index lookup for reordered fields once a name mismatch is observed. + // Because field names within a Schema are unique and counts match, checking every field of + // this schema against other.fieldIndices verifies a full bijection in O(N) time without + // sorting. + int i = 0; + for (; i < count; ++i) { + Field actualField = fields.get(i); + Field otherField = other.fields.get(i); + if (!actualField.getName().equals(otherField.getName())) { + break; + } + if (!actualField.getType().equivalent(otherField.getType(), nullablePolicy)) { + return false; + } + } + for (; i < count; ++i) { + Field actualField = fields.get(i); + Integer otherIdx = other.fieldIndices.get(actualField.getName()); + if (otherIdx == null) { + return false; + } + if (!actualField.getType().equivalent(other.fields.get(otherIdx).getType(), nullablePolicy)) { return false; } } @@ -541,35 +709,55 @@ public enum TypeName { public static final Set COMPOSITE_TYPES = ImmutableSet.of(ROW); public boolean isPrimitiveType() { - return !isCollectionType() && !isMapType() && !isCompositeType() && !isLogicalType(); + switch (this) { + case ARRAY: + case ITERABLE: + case MAP: + case ROW: + case LOGICAL_TYPE: + return false; + default: + return true; + } } public boolean isNumericType() { - return NUMERIC_TYPES.contains(this); + switch (this) { + case BYTE: + case INT16: + case INT32: + case INT64: + case DECIMAL: + case FLOAT: + case DOUBLE: + return true; + default: + return false; + } } public boolean isStringType() { - return STRING_TYPES.contains(this); + return this == STRING; } public boolean isDateType() { - return DATE_TYPES.contains(this); + return this == DATETIME; } public boolean isCollectionType() { - return COLLECTION_TYPES.contains(this); + return this == ARRAY || this == ITERABLE; } public boolean isMapType() { - return MAP_TYPES.contains(this); + return this == MAP; } public boolean isCompositeType() { - return COMPOSITE_TYPES.contains(this); + return this == ROW; } public boolean isLogicalType() { - return this.equals(LOGICAL_TYPE); + return this == LOGICAL_TYPE; } public boolean isSubtypeOf(TypeName other) { @@ -796,6 +984,21 @@ public static FieldType of(TypeName typeName) { /** The type of datetime fields. */ public static final FieldType DATETIME = FieldType.of(TypeName.DATETIME); + private static final FieldType NULLABLE_STRING = STRING.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_BYTE = BYTE.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_BYTES = BYTES.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_INT16 = INT16.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_INT32 = INT32.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_INT64 = INT64.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_FLOAT = FLOAT.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_DOUBLE = DOUBLE.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_DECIMAL = DECIMAL.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_BOOLEAN = BOOLEAN.toBuilder().setNullable(true).build(); + private static final FieldType NULLABLE_DATETIME = + DATETIME.toBuilder().setNullable(true).build(); + + private transient int cachedHashCode; + /** Create an array type for the given field type. */ public static FieldType array(FieldType elementType) { return FieldType.forTypeName(TypeName.ARRAY).setCollectionElementType(elementType).build(); @@ -923,51 +1126,95 @@ public String getMetadataString(String key) { } public FieldType withNullable(boolean nullable) { + if (getNullable() == nullable) { + return this; + } + TypeName typeName = getTypeName(); + if (typeName.isPrimitiveType() && getMetadata().isEmpty()) { + switch (typeName) { + case STRING: + return nullable ? NULLABLE_STRING : STRING; + case BYTE: + return nullable ? NULLABLE_BYTE : BYTE; + case BYTES: + return nullable ? NULLABLE_BYTES : BYTES; + case INT16: + return nullable ? NULLABLE_INT16 : INT16; + case INT32: + return nullable ? NULLABLE_INT32 : INT32; + case INT64: + return nullable ? NULLABLE_INT64 : INT64; + case FLOAT: + return nullable ? NULLABLE_FLOAT : FLOAT; + case DOUBLE: + return nullable ? NULLABLE_DOUBLE : DOUBLE; + case DECIMAL: + return nullable ? NULLABLE_DECIMAL : DECIMAL; + case BOOLEAN: + return nullable ? NULLABLE_BOOLEAN : BOOLEAN; + case DATETIME: + return nullable ? NULLABLE_DATETIME : DATETIME; + default: + break; + } + } return toBuilder().setNullable(nullable).build(); } @Override public final boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } if (!(o instanceof FieldType)) { return false; } FieldType other = (FieldType) o; - if (getTypeName().isLogicalType()) { - if (!other.getTypeName().isLogicalType()) { - return false; - } - if (!Objects.equals( - getLogicalType().getIdentifier(), other.getLogicalType().getIdentifier())) { - return false; - } - if (getLogicalType().getArgument() == null) { - if (other.getLogicalType().getArgument() != null) { - return false; - } - } else { - if (!getLogicalType() - .getArgumentType() - .equals(other.getLogicalType().getArgumentType())) { - return false; - } - // Only check argument equality if argument type is non-null. null indicates argument is - // ignored. - if (!Row.Equals.deepEquals( - getLogicalType().getArgument(), - other.getLogicalType().getArgument(), - getLogicalType().getArgumentType())) { - return false; + TypeName tn = getTypeName(); + if (tn != other.getTypeName() || getNullable() != other.getNullable()) { + return false; + } + switch (tn) { + case LOGICAL_TYPE: + LogicalType thisLt = getLogicalType(); + LogicalType otherLt = other.getLogicalType(); + if (thisLt != otherLt) { + if (!Objects.equals(thisLt.getIdentifier(), otherLt.getIdentifier())) { + return false; + } + Object thisArg = thisLt.getArgument(); + Object otherArg = otherLt.getArgument(); + if (thisArg == null) { + if (otherArg != null) { + return false; + } + } else { + if (!Objects.equals(thisLt.getArgumentType(), otherLt.getArgumentType())) { + return false; + } + // Only check argument equality if argument type is non-null. null indicates argument + // is ignored. + if (!Row.Equals.deepEquals(thisArg, otherArg, thisLt.getArgumentType())) { + return false; + } + } } - } + return Objects.equals(getMetadata(), other.getMetadata()); + case ARRAY: + case ITERABLE: + return Objects.equals(getCollectionElementType(), other.getCollectionElementType()) + && Objects.equals(getMetadata(), other.getMetadata()); + case MAP: + return Objects.equals(getMapKeyType(), other.getMapKeyType()) + && Objects.equals(getMapValueType(), other.getMapValueType()) + && Objects.equals(getMetadata(), other.getMetadata()); + case ROW: + return Objects.equals(getRowSchema(), other.getRowSchema()) + && Objects.equals(getMetadata(), other.getMetadata()); + default: + return Objects.equals(getMetadata(), other.getMetadata()); } - return Objects.equals(getTypeName(), other.getTypeName()) - && getNullable() == other.getNullable() - && Objects.equals(getCollectionElementType(), other.getCollectionElementType()) - && Objects.equals(getMapKeyType(), other.getMapKeyType()) - && Objects.equals(getMapValueType(), other.getMapValueType()) - && Objects.equals(getRowSchema(), other.getRowSchema()) - && Objects.equals(getMetadata(), other.getMetadata()); } /** Returns true if two FieldTypes are equal. */ @@ -1017,7 +1264,11 @@ public boolean typesEqual(FieldType other) { } /** Check whether two types are equivalent. */ + @SuppressWarnings("ReferenceEquality") public boolean equivalent(FieldType other, EquivalenceNullablePolicy nullablePolicy) { + if (this == other) { + return true; + } if (nullablePolicy == EquivalenceNullablePolicy.SAME && other.getNullable() != getNullable()) { return false; @@ -1027,7 +1278,7 @@ public boolean equivalent(FieldType other, EquivalenceNullablePolicy nullablePol } } - if (!getTypeName().equals(other.getTypeName())) { + if (getTypeName() != other.getTypeName()) { return false; } @@ -1058,16 +1309,20 @@ public boolean equivalent(FieldType other, EquivalenceNullablePolicy nullablePol @Override public final int hashCode() { - return Arrays.deepHashCode( - new Object[] { - getTypeName(), - getNullable(), - getCollectionElementType(), - getMapKeyType(), - getMapValueType(), - getRowSchema(), - getMetadata() - }); + int h = cachedHashCode; + if (h != 0) { + return h; + } + int result = 1; + result = 31 * result + Objects.hashCode(getTypeName()); + result = 31 * result + Boolean.hashCode(getNullable()); + result = 31 * result + Objects.hashCode(getCollectionElementType()); + result = 31 * result + Objects.hashCode(getMapKeyType()); + result = 31 * result + Objects.hashCode(getMapValueType()); + result = 31 * result + Objects.hashCode(getRowSchema()); + result = 31 * result + Objects.hashCode(getMetadata()); + cachedHashCode = result; + return result; } @Override @@ -1198,15 +1453,20 @@ public Field withOptions(Options.Builder optionsBuilder) { return withOptions(optionsBuilder.build()); } + private transient int cachedHashCode; + @Override public final boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } if (!(o instanceof Field)) { return false; } Field other = (Field) o; return Objects.equals(getName(), other.getName()) - && Objects.equals(getDescription(), other.getDescription()) && Objects.equals(getType(), other.getType()) + && Objects.equals(getDescription(), other.getDescription()) && Objects.equals(getOptions(), other.getOptions()); } @@ -1215,18 +1475,23 @@ public boolean typesEqual(Field other) { return getType().typesEqual(other.getType()); } - private boolean equivalent(Field otherField, EquivalenceNullablePolicy nullablePolicy) { - return getName().equals(otherField.getName()) - && getType().equivalent(otherField.getType(), nullablePolicy); - } - @Override public final int hashCode() { - return Objects.hash(getName(), getDescription(), getType()); + int h = cachedHashCode; + if (h != 0) { + return h; + } + int result = 1; + result = 31 * result + Objects.hashCode(getName()); + result = 31 * result + Objects.hashCode(getDescription()); + result = 31 * result + Objects.hashCode(getType()); + cachedHashCode = result; + return result; } } public static class Options implements Serializable { + private static final Options NONE = new Options(Collections.emptyMap()); private final Map options; @Override @@ -1260,6 +1525,12 @@ public boolean equals(@Nullable Object o) { return false; } Options options1 = (Options) o; + if (options.isEmpty() && options1.options.isEmpty()) { + return true; + } + if (options.size() != options1.options.size()) { + return false; + } if (!options.keySet().equals(options1.options.keySet())) { return false; } @@ -1328,7 +1599,7 @@ public static class Builder { } Builder() { - this(new HashMap<>()); + this.options = new HashMap<>(); } public Builder setOption(String optionName, Row value) { @@ -1352,7 +1623,10 @@ public Builder setOption(String optionName, FieldType fieldType, Object value) { } public Options build() { - return new Options(this.options); + if (this.options.isEmpty()) { + return NONE; + } + return new Options(new HashMap<>(this.options)); } public Builder addOptions(Options options) { @@ -1370,7 +1644,7 @@ public Builder addOptions(Options options) { } Options.Builder toBuilder() { - return new Builder(new HashMap<>(this.options)); + return this.options.isEmpty() ? new Builder() : new Builder(this.options); } public static Options.Builder builder() { @@ -1378,7 +1652,7 @@ public static Options.Builder builder() { } public static Options none() { - return new Options(); + return NONE; } /** Get the value of an option. If the option is not found null is returned. */ @@ -1441,9 +1715,19 @@ private static Schema fromFields(List fields) { return new Schema(fields); } - /** Return the list of all field names. */ + /** Return an unmodifiable list of all field names. */ public List<@NonNull String> getFieldNames() { - return getFields().stream().map(Schema.Field::getName).collect(Collectors.toList()); + List<@NonNull String> names = cachedFieldNames; + if (names == null) { + ImmutableList.Builder<@NonNull String> builder = + ImmutableList.builderWithExpectedSize(fields.size()); + for (int i = 0; i < fields.size(); i++) { + builder.add(fields.get(i).getName()); + } + names = builder.build(); + cachedFieldNames = names; + } + return names; } /** Return a field by index. */ @@ -1470,9 +1754,10 @@ public boolean hasField(String fieldName) { /** Return the name of field by index. */ public String nameOf(int fieldIndex) { - String name = fieldIndices.inverse().get(fieldIndex); - Preconditions.checkArgument(name != null, "Cannot find field %s", fieldIndex); - return name; + if (fieldIndex < 0 || fieldIndex >= fields.size()) { + throw new IllegalArgumentException("Cannot find field " + fieldIndex); + } + return fields.get(fieldIndex).getName(); } /** Return the count of fields. */ diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaUtils.java index d45454be90fa..1639e0d54546 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaUtils.java @@ -17,12 +17,18 @@ */ package org.apache.beam.sdk.schemas; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.Objects; +import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.schemas.Schema.LogicalType; +import org.apache.beam.sdk.transforms.SerializableFunction; +import org.apache.beam.sdk.transforms.SerializableFunctions; import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; /** A set of utility functions for schemas. */ @SuppressWarnings({ @@ -30,6 +36,96 @@ }) public class SchemaUtils { private static final String INDENT = " "; + private static final Class IDENTITY_FN_CLASS = SerializableFunctions.identity().getClass(); + + /** + * Returns {@code true} if {@code fn} is Beam's built-in identity {@link SerializableFunction} + * returned by {@link SerializableFunctions#identity()}. + */ + @Internal + public static boolean isIdentityFunction(@Nullable SerializableFunction fn) { + return fn != null && fn.getClass() == IDENTITY_FN_CLASS; + } + + /** + * Attempts to resolve a single-field non-wildcard, qualifier-free {@link FieldAccessDescriptor} + * into an array of field indices from {@code schema} down to the leaf field, or returns {@code + * null} if the descriptor cannot be evaluated via direct indexed traversal. + */ + @Internal + public static int @Nullable [] tryResolveSingleFieldPath( + Schema schema, FieldAccessDescriptor resolved) { + if (resolved.getAllFields()) { + return null; + } + Schema current = schema; + FieldAccessDescriptor cur = resolved; + List path = new ArrayList<>(4); + while (true) { + Map nested = + cur.getNestedFieldsAccessed(); + if (!cur.getFieldsAccessed().isEmpty()) { + if (!nested.isEmpty() || cur.getFieldsAccessed().size() != 1) { + return null; + } + FieldAccessDescriptor.FieldDescriptor fd = cur.getFieldsAccessed().iterator().next(); + if (!fd.getQualifiers().isEmpty()) { + return null; + } + Integer id = fd.getFieldId(); + if (id == null || id < 0 || id >= current.getFieldCount()) { + return null; + } + path.add(id); + int[] arr = new int[path.size()]; + for (int i = 0; i < arr.length; i++) { + arr[i] = path.get(i); + } + return arr; + } + if (nested.size() != 1) { + return null; + } + Map.Entry entry = + nested.entrySet().iterator().next(); + FieldAccessDescriptor.FieldDescriptor fd = entry.getKey(); + if (!fd.getQualifiers().isEmpty()) { + return null; + } + Integer id = fd.getFieldId(); + if (id == null || id < 0 || id >= current.getFieldCount()) { + return null; + } + FieldType ft = current.getField(id).getType(); + if (ft.getTypeName() != Schema.TypeName.ROW || ft.getRowSchema() == null) { + return null; + } + path.add(id); + current = ft.getRowSchema(); + cur = entry.getValue(); + if (cur.getAllFields()) { + return null; + } + } + } + + /** Evaluates a direct index path produced by {@link #tryResolveSingleFieldPath}. */ + @Internal + public static @Nullable Object readFieldPath(@Nullable Row row, int[] path) { + if (row == null) { + return null; + } + Row current = row; + int last = path.length - 1; + for (int i = 0; i < last; i++) { + Object next = current.getValue(path[i]); + if (next == null) { + return null; + } + current = (Row) next; + } + return current.getValue(path[last]); + } /** * Given two schema that have matching types, return a nullable-widened schema. @@ -382,32 +478,30 @@ static String toPrettySchemaString(Schema schema, String prefix) { } static String toPrettyRowString(Row row, String prefix) { - long nonNullFieldCount = row.getValues().stream().filter(Objects::nonNull).count(); - if (nonNullFieldCount == 0) { - return "{}"; - } - + Schema schema = row.getSchema(); + int fieldCount = schema.getFieldCount(); String nextPrefix = prefix + INDENT; - StringBuilder sb = new StringBuilder(); - sb.append("{\n"); - long nonNullFieldIndex = 0; - for (Schema.Field field : row.getSchema().getFields()) { - String fieldName = field.getName(); - Object fieldValue = row.getValue(fieldName); + StringBuilder sb = null; + for (int i = 0; i < fieldCount; i++) { + Object fieldValue = row.getValue(i); if (fieldValue == null) { continue; } + Schema.Field field = schema.getField(i); + if (sb == null) { + sb = new StringBuilder("{\n"); + } else { + sb.append(",\n"); + } sb.append(nextPrefix) - .append(fieldName) + .append(field.getName()) .append(": ") .append(toPrettyFieldValueString(field.getType(), fieldValue, nextPrefix)); - if (nonNullFieldIndex++ < nonNullFieldCount - 1) { - sb.append(",\n"); - } else { - sb.append("\n"); - } } - sb.append(prefix).append("}"); + if (sb == null) { + return "{}"; + } + sb.append('\n').append(prefix).append('}'); return sb.toString(); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/Row.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/Row.java index 6eb063f84b67..b57a1e49bc0a 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/Row.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/Row.java @@ -33,7 +33,6 @@ import java.util.Objects; import java.util.stream.Collector; import java.util.stream.Collectors; -import java.util.stream.IntStream; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.schemas.Factory; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; @@ -48,6 +47,7 @@ import org.apache.beam.sdk.values.RowUtils.RowFieldMatcher; import org.apache.beam.sdk.values.RowUtils.RowPosition; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; +import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.joda.time.DateTime; import org.joda.time.ReadableDateTime; @@ -108,9 +108,23 @@ public abstract class Row implements Serializable { /** Return a list of data values. Any LogicalType values are returned as base values. * */ public List getBaseValues() { - return IntStream.range(0, getFieldCount()) - .mapToObj(i -> getBaseValue(i)) - .collect(Collectors.toList()); + int count = getFieldCount(); + Schema s = getSchema(); + if (!s.hasLogicalTypes()) { + if (this instanceof RowWithStorage) { + return new ArrayList<>(getValues()); + } + List result = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + result.add(getValue(i)); + } + return result; + } + List result = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + result.add(getBaseValue(i)); + } + return result; } /** Get value by field name, {@link ClassCastException} is thrown if type doesn't match. */ @@ -332,7 +346,13 @@ public List getBaseValues() { */ public @Nullable ReadableDateTime getDateTime(int idx) { ReadableInstant instant = getValue(idx); - return instant == null ? null : new DateTime(instant).withZone(instant.getZone()); + if (instant == null) { + return null; + } + if (instant instanceof DateTime) { + return (DateTime) instant; + } + return new DateTime(instant.getMillis(), instant.getZone()); } /** @@ -432,12 +452,18 @@ public boolean equals(@Nullable Object o) { } Row other = (Row) o; - if (!Objects.equals(getSchema(), other.getSchema())) { + Schema localSchema = getSchema(); + Schema otherSchema = other.getSchema(); + if (!Objects.equals(localSchema, otherSchema)) { return false; } - for (int i = 0; i < getFieldCount(); i++) { - if (!Equals.deepEquals(getValue(i), other.getValue(i), getSchema().getField(i).getType())) { + int count = getFieldCount(); + if (count != other.getFieldCount()) { + return false; + } + for (int i = 0; i < count; i++) { + if (!Equals.deepEquals(getValue(i), other.getValue(i), localSchema.getField(i).getType())) { return false; } } @@ -447,9 +473,11 @@ public boolean equals(@Nullable Object o) { @Override public int hashCode() { + Schema localSchema = getSchema(); + int count = getFieldCount(); int h = 1; - for (int i = 0; i < getFieldCount(); i++) { - h = 31 * h + Equals.deepHashCode(getValue(i), getSchema().getField(i).getType()); + for (int i = 0; i < count; i++) { + h = 31 * h + Equals.deepHashCode(getValue(i), localSchema.getField(i).getType()); } return h; @@ -457,45 +485,57 @@ public int hashCode() { public static class Equals { public static boolean deepEquals(Object a, Object b, Schema.FieldType fieldType) { + if (a == b) { + return true; + } if (a == null || b == null) { - return a == b; - } else if (fieldType.getTypeName() == TypeName.LOGICAL_TYPE) { - Schema.LogicalType logicalType = - (Schema.LogicalType) fieldType.getLogicalType(); - return deepEquals( - SchemaUtils.toLogicalBaseType(logicalType, a), - SchemaUtils.toLogicalBaseType(logicalType, b), - logicalType.getBaseType()); - } else if (fieldType.getTypeName() == Schema.TypeName.BYTES) { - return Arrays.equals((byte[]) a, (byte[]) b); - } else if (fieldType.getTypeName() == TypeName.ARRAY) { - return deepEqualsForCollection( - (Collection) a, (Collection) b, fieldType.getCollectionElementType()); - } else if (fieldType.getTypeName() == TypeName.ITERABLE) { - return deepEqualsForIterable( - (Iterable) a, (Iterable) b, fieldType.getCollectionElementType()); - } else if (fieldType.getTypeName() == Schema.TypeName.MAP) { - return deepEqualsForMap( - (Map) a, (Map) b, fieldType.getMapValueType()); - } else { - return Objects.equals(a, b); + return false; + } + switch (fieldType.getTypeName()) { + case LOGICAL_TYPE: + Schema.LogicalType logicalType = + (Schema.LogicalType) fieldType.getLogicalType(); + return deepEquals( + SchemaUtils.toLogicalBaseType(logicalType, a), + SchemaUtils.toLogicalBaseType(logicalType, b), + logicalType.getBaseType()); + case BYTES: + return Arrays.equals((byte[]) a, (byte[]) b); + case ARRAY: + return deepEqualsForCollection( + (Collection) a, (Collection) b, fieldType.getCollectionElementType()); + case ITERABLE: + return deepEqualsForIterable( + (Iterable) a, (Iterable) b, fieldType.getCollectionElementType()); + case MAP: + return deepEqualsForMap( + (Map) a, (Map) b, fieldType.getMapValueType()); + default: + return a.equals(b); } } public static int deepHashCode(Object a, Schema.FieldType fieldType) { if (a == null) { return 0; - } else if (fieldType.getTypeName() == TypeName.LOGICAL_TYPE) { - return deepHashCode(a, fieldType.getLogicalType().getBaseType()); - } else if (fieldType.getTypeName() == Schema.TypeName.BYTES) { - return Arrays.hashCode((byte[]) a); - } else if (fieldType.getTypeName().isCollectionType()) { - return deepHashCodeForIterable((Iterable) a, fieldType.getCollectionElementType()); - } else if (fieldType.getTypeName() == Schema.TypeName.MAP) { - return deepHashCodeForMap( - (Map) a, fieldType.getMapKeyType(), fieldType.getMapValueType()); - } else { - return Objects.hashCode(a); + } + switch (fieldType.getTypeName()) { + case LOGICAL_TYPE: + Schema.LogicalType logicalType = + (Schema.LogicalType) fieldType.getLogicalType(); + return deepHashCode( + SchemaUtils.toLogicalBaseType(logicalType, a), logicalType.getBaseType()); + case BYTES: + return Arrays.hashCode((byte[]) a); + case ARRAY: + case ITERABLE: + return deepHashCodeForIterable( + (Iterable) a, fieldType.getCollectionElementType()); + case MAP: + return deepHashCodeForMap( + (Map) a, fieldType.getMapKeyType(), fieldType.getMapValueType()); + default: + return a.hashCode(); } } @@ -589,57 +629,64 @@ public String toString() { /** Convert Row to String. */ public String toString(boolean includeFieldNames) { StringBuilder builder = new StringBuilder(); - builder.append("Row: "); - builder.append(System.lineSeparator()); - for (int i = 0; i < getSchema().getFieldCount(); ++i) { - Schema.Field field = getSchema().getField(i); + appendToString(builder, includeFieldNames); + return builder.toString(); + } + + private void appendToString(StringBuilder builder, boolean includeFieldNames) { + Schema s = getSchema(); + String lineSep = System.lineSeparator(); + builder.append("Row: ").append(lineSep); + int fieldCount = s.getFieldCount(); + for (int i = 0; i < fieldCount; ++i) { + Schema.Field field = s.getField(i); if (includeFieldNames) { - builder.append(field.getName() + ":"); + builder.append(field.getName()).append(':'); } - builder.append(toString(field.getType(), getValue(i), includeFieldNames)); - builder.append(System.lineSeparator()); + appendFieldValueToString(builder, field.getType(), getValue(i), includeFieldNames); + builder.append(lineSep); } - return builder.toString(); } - private String toString(Schema.FieldType fieldType, Object value, boolean includeFieldNames) { + private static void appendFieldValueToString( + StringBuilder builder, Schema.FieldType fieldType, Object value, boolean includeFieldNames) { if (value == null) { - return ""; + builder.append(""); + return; } - StringBuilder builder = new StringBuilder(); switch (fieldType.getTypeName()) { case ARRAY: case ITERABLE: - builder.append("["); + builder.append('['); for (Object element : (Iterable) value) { - builder.append( - toString(fieldType.getCollectionElementType(), element, includeFieldNames)); + appendFieldValueToString( + builder, fieldType.getCollectionElementType(), element, includeFieldNames); builder.append(", "); } - builder.append("]"); + builder.append(']'); break; case MAP: - builder.append("{"); + builder.append('{'); for (Map.Entry entry : ((Map) value).entrySet()) { - builder.append("("); - builder.append(toString(fieldType.getMapKeyType(), entry.getKey(), includeFieldNames)); + builder.append('('); + appendFieldValueToString( + builder, fieldType.getMapKeyType(), entry.getKey(), includeFieldNames); builder.append(", "); - builder.append( - toString(fieldType.getMapValueType(), entry.getValue(), includeFieldNames)); + appendFieldValueToString( + builder, fieldType.getMapValueType(), entry.getValue(), includeFieldNames); builder.append("), "); } - builder.append("}"); + builder.append('}'); break; case BYTES: builder.append(Arrays.toString((byte[]) value)); break; case ROW: - builder.append(((Row) value).toString(includeFieldNames)); + ((Row) value).appendToString(builder, includeFieldNames); break; default: builder.append(value); } - return builder.toString(); } /** @@ -816,12 +863,10 @@ public Builder addIterable(Iterable values) { return this; } - // Values are attached. No verification is done, and no conversions are done. LogicalType values - // must be specified as the base type. This method should be used with great care, as no - // validation is done. If - // incorrect values are passed in, it could result in strange errors later in the pipeline. This - // method is largely - // used internal to Beam. + // Values are attached without validation or conversion. LogicalType values must match the + // LogicalType's InputT (not BaseT). This method should be used with great care, as no + // validation is done. If incorrect values are passed in, it could result in errors later in + // the pipeline. Largely used internal to Beam. @Internal public Row attachValues(List<@Nullable Object> attachedValues) { checkState(this.values.isEmpty()); @@ -829,7 +874,8 @@ public Row attachValues(List<@Nullable Object> attachedValues) { } public Row attachValues(@Nullable Object... values) { - return attachValues(Arrays.asList(values)); + checkState(this.values.isEmpty()); + return new RowWithStorage(schema, values); } public int nextFieldId() { @@ -890,6 +936,53 @@ public static Collector, Row> toRow(Schema schema) { values -> Row.withSchema(schema).addValues(values).build()); } + /** + * Direct internal factory that attaches a backing array to a {@link RowWithStorage} without + * creating a throwaway {@link Builder} or {@code Arrays$ArrayList} wrapper. Values are NOT + * validated or converted; callers MUST NOT mutate the passed array afterwards. + */ + @Internal + public static Row attachValues(Schema schema, @Nullable Object... values) { + return new RowWithStorage(schema, values); + } + + /** + * Direct internal factory that attaches a backing {@link List} to a {@link RowWithStorage} + * without creating a throwaway {@link Builder}. Values are NOT validated or converted. + */ + @Internal + public static Row attachValues(Schema schema, List<@Nullable Object> values) { + return new RowWithStorage(schema, values); + } + + /** + * Direct internal factory creating a {@link RowWithGetters} using a {@link Factory}, bypassing + * {@link Builder} allocation. + */ + @Internal + public static Row withFieldValueGetters( + Schema schema, + Factory>> fieldValueGetterFactory, + T getterTarget, + TypeDescriptor getterTargetType) { + checkState(getterTarget != null, "getters require withGetterTarget."); + return new RowWithGetters<>(schema, fieldValueGetterFactory, getterTarget, getterTargetType); + } + + /** + * Direct internal factory creating a {@link RowWithGetters} with a pre-resolved getter list, + * bypassing both {@link Builder} allocation and {@link Factory} cache lookup. + */ + @Internal + public static Row withFieldValueGetters( + Schema schema, + List> getters, + T getterTarget, + TypeDescriptor getterTargetType) { + checkState(getterTarget != null, "getters require withGetterTarget."); + return new RowWithGetters<>(schema, getters, getterTarget, getterTargetType); + } + /** Creates a new record filled with nulls. */ public static Row nullRow(Schema schema) { return Row.withSchema(schema) @@ -899,50 +992,50 @@ public static Row nullRow(Schema schema) { /** Returns an equivalent {@link Row} with fields lexicographically sorted by their name. */ public Row sorted() { - Schema sortedSchema = getSchema().sorted(); - return sortedSchema.getFields().stream() - .map( - field -> { - if (field.getType().getRowSchema() != null) { - Row innerRow = getValue(field.getName()); - if (innerRow != null) { - return innerRow.sorted(); - } - } - return (Object) getValue(field.getName()); - }) - .collect(Row.toRow(sortedSchema)); + Schema sourceSchema = getSchema(); + Schema sortedSchema = sourceSchema.sorted(); + int count = sortedSchema.getFieldCount(); + @Nullable Object[] outValues = new Object[count]; + for (int i = 0; i < count; i++) { + Schema.Field field = sortedSchema.getField(i); + Object val = getValue(sourceSchema.indexOf(field.getName())); + if (val != null && field.getType().getRowSchema() != null) { + val = ((Row) val).sorted(); + } + outValues[i] = val; + } + return new RowWithStorage(sortedSchema, outValues); } /** Returns an equivalent {@link Row} with `snake_case` field names. */ public Row toSnakeCase() { - return getSchema().getFields().stream() - .map( - field -> { - if (field.getType().getRowSchema() != null) { - Row innerRow = getValue(field.getName()); - if (innerRow != null) { - return innerRow.toSnakeCase(); - } - } - return (Object) getValue(field.getName()); - }) - .collect(toRow(getSchema().toSnakeCase())); + Schema sourceSchema = getSchema(); + Schema targetSchema = sourceSchema.toSnakeCase(); + int count = sourceSchema.getFieldCount(); + @Nullable Object[] outValues = new Object[count]; + for (int i = 0; i < count; i++) { + Object val = getValue(i); + if (val != null && sourceSchema.getField(i).getType().getRowSchema() != null) { + val = ((Row) val).toSnakeCase(); + } + outValues[i] = val; + } + return new RowWithStorage(targetSchema, outValues); } /** Returns an equivalent {@link Row} with `lowerCamelCase` field names. */ public Row toCamelCase() { - return getSchema().getFields().stream() - .map( - field -> { - if (field.getType().getRowSchema() != null) { - Row innerRow = getValue(field.getName()); - if (innerRow != null) { - return innerRow.toCamelCase(); - } - } - return (Object) getValue(field.getName()); - }) - .collect(toRow(getSchema().toCamelCase())); + Schema sourceSchema = getSchema(); + Schema targetSchema = sourceSchema.toCamelCase(); + int count = sourceSchema.getFieldCount(); + @Nullable Object[] outValues = new Object[count]; + for (int i = 0; i < count; i++) { + Object val = getValue(i); + if (val != null && sourceSchema.getField(i).getType().getRowSchema() != null) { + val = ((Row) val).toCamelCase(); + } + outValues[i] = val; + } + return new RowWithStorage(targetSchema, outValues); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithGetters.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithGetters.java index 0cbc7bfb992a..a95193383695 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithGetters.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithGetters.java @@ -17,20 +17,13 @@ */ package org.apache.beam.sdk.values; -import static org.apache.beam.sdk.util.Preconditions.checkStateNotNull; - import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.TreeMap; -import java.util.function.Function; +import java.util.concurrent.atomic.AtomicReferenceArray; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.schemas.Factory; import org.apache.beam.sdk.schemas.FieldValueGetter; import org.apache.beam.sdk.schemas.Schema; -import org.apache.beam.sdk.schemas.Schema.Field; -import org.apache.beam.sdk.schemas.Schema.TypeName; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -43,54 +36,61 @@ */ @SuppressWarnings("rawtypes") public class RowWithGetters extends Row { + private static final Object NULL_SENTINEL = new Object(); + private final T getterTarget; private final TypeDescriptor getterTargetType; private final List> getters; - private @Nullable Map cache = null; + // Null slot means uncached; NULL_SENTINEL means cached null. AtomicReferenceArray ensures + // safe JMM publication of cached collections across concurrent readers. + private transient volatile @Nullable AtomicReferenceArray<@Nullable Object> cache = null; RowWithGetters( Schema schema, Factory>> getterFactory, T getterTarget, TypeDescriptor getterTargetType) { + this(schema, getterFactory.create(getterTargetType, schema), getterTarget, getterTargetType); + } + + RowWithGetters( + Schema schema, + List> getters, + T getterTarget, + TypeDescriptor getterTargetType) { super(schema); this.getterTarget = getterTarget; this.getterTargetType = getterTargetType; - this.getters = getterFactory.create(getterTargetType, schema); + this.getters = getters; } @Override @SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"}) public W getValue(int fieldIdx) { - Field field = getSchema().getField(fieldIdx); - boolean cacheField = cacheFieldType(field); - - if (cacheField && cache == null) { - cache = new TreeMap<>(); - } - + Schema schema = getSchema(); @Nullable Object fieldValue; - if (cacheField) { - if (cache == null) { - cache = new TreeMap<>(); + int cacheSlot = schema.getContainerCacheSlot(fieldIdx); + if (cacheSlot >= 0) { + AtomicReferenceArray<@Nullable Object> localCache = cache; + if (localCache == null) { + localCache = new AtomicReferenceArray<>(schema.getCacheableContainerCount()); + cache = localCache; + } + @Nullable Object cached = localCache.get(cacheSlot); + if (cached == null) { + FieldValueGetter getter = getters.get(fieldIdx); + fieldValue = getter.get(getterTarget); + localCache.set(cacheSlot, fieldValue == null ? NULL_SENTINEL : fieldValue); + } else { + fieldValue = cached == NULL_SENTINEL ? null : cached; } - fieldValue = - cache.computeIfAbsent( - fieldIdx, - new Function() { - @Override - public @Nullable Object apply(Integer idx) { - FieldValueGetter getter = getters.get(idx); - checkStateNotNull(getter); - return getter.get(getterTarget); - } - }); } else { fieldValue = getters.get(fieldIdx).get(getterTarget); } - if (fieldValue == null && !field.getType().getNullable()) { - throw new RuntimeException("Null value set on non-nullable field " + field); + if (fieldValue == null && !schema.isFieldNullable(fieldIdx)) { + throw new RuntimeException( + "Null value set on non-nullable field " + schema.getField(fieldIdx)); } return (W) fieldValue; } @@ -99,13 +99,6 @@ public TypeDescriptor getGetterTargetType() { return getterTargetType; } - private boolean cacheFieldType(Field field) { - TypeName typeName = field.getType().getTypeName(); - return typeName.equals(TypeName.MAP) - || typeName.equals(TypeName.ARRAY) - || typeName.equals(TypeName.ITERABLE); - } - @Override public int getFieldCount() { return getters.size(); @@ -116,8 +109,8 @@ public int getFieldCount() { @Override public List<@Nullable Object> getValues() { List<@Nullable Object> rawValues = new ArrayList<>(getters.size()); - for (FieldValueGetter getter : getters) { - rawValues.add(getter.getRaw(getterTarget)); + for (int i = 0; i < getters.size(); i++) { + rawValues.add(getters.get(i).getRaw(getterTarget)); } return rawValues; } @@ -140,8 +133,13 @@ public boolean equals(@Nullable Object o) { } if (o instanceof RowWithGetters) { RowWithGetters other = (RowWithGetters) o; - return Objects.equals(getSchema(), other.getSchema()) - && Objects.equals(getterTarget, other.getterTarget); + if (!getSchema().equals(other.getSchema())) { + return false; + } + if (getterTarget == other.getterTarget) { + return true; + } + return super.equals(o); } else if (o instanceof Row) { return super.equals(o); } @@ -150,6 +148,6 @@ public boolean equals(@Nullable Object o) { @Override public int hashCode() { - return Objects.hash(getSchema(), getterTarget); + return super.hashCode(); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithStorage.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithStorage.java index cba99db43cc3..48e2610e12d3 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithStorage.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/RowWithStorage.java @@ -17,36 +17,85 @@ */ package org.apache.beam.sdk.values; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.util.Arrays; import java.util.List; +import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.schemas.Schema; import org.checkerframework.checker.nullness.qual.Nullable; /** Concrete subclass of {@link Row} that explicitly stores all fields of the row. */ public class RowWithStorage extends Row { - private final List<@Nullable Object> values; + private @Nullable List<@Nullable Object> values; + private final @Nullable Object @Nullable [] arrayValues; RowWithStorage(Schema schema, List<@Nullable Object> values) { super(schema); this.values = values; + this.arrayValues = null; + } + + RowWithStorage(Schema schema, @Nullable Object[] arrayValues) { + super(schema); + this.values = null; + this.arrayValues = arrayValues; } @Override - @SuppressWarnings("TypeParameterUnusedInFormals") + @SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"}) public T getValue(int fieldIdx) { - if (values.size() > fieldIdx) { - return (T) values.get(fieldIdx); - } else { + @Nullable Object @Nullable [] arr = arrayValues; + if (arr != null) { + if (fieldIdx >= 0 && fieldIdx < arr.length) { + return (T) arr[fieldIdx]; + } throw new IllegalArgumentException("No field at index " + fieldIdx); } + List<@Nullable Object> list = values; + if (list != null && fieldIdx >= 0 && fieldIdx < list.size()) { + return (T) list.get(fieldIdx); + } + throw new IllegalArgumentException("No field at index " + fieldIdx); + } + + /** + * Returns the backing array directly when this row was created from an array, or {@code null} if + * backed by a {@link List}. Callers MUST NOT mutate the returned array. + */ + @Internal + public @Nullable Object @Nullable [] getRawArray() { + return arrayValues; } @Override public List<@Nullable Object> getValues() { - return values; + List<@Nullable Object> list = values; + if (list == null) { + @Nullable Object @Nullable [] arr = arrayValues; + if (arr == null) { + throw new IllegalStateException("RowWithStorage has neither values list nor array"); + } + list = Arrays.asList(arr); + values = list; + } + return list; } @Override public int getFieldCount() { - return values.size(); + @Nullable Object @Nullable [] arr = arrayValues; + if (arr != null) { + return arr.length; + } + List<@Nullable Object> list = values; + return list != null ? list.size() : 0; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + ObjectOutputStream.PutField fields = out.putFields(); + fields.put("values", arrayValues != null ? null : values); + fields.put("arrayValues", arrayValues); + out.writeFields(); } } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTest.java index 5f3749120496..d79a0202db04 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/SchemaTest.java @@ -348,7 +348,14 @@ public void testSortedMethodIncludesAllSchemaFields() { "fields", "hashCode", "uuid", - "options"); + "options", + // Derived transient/static metadata caches recomputed lazily per Schema instance. + "FLAG_HAS_NULLABLE_FIELDS", + "FLAG_HAS_LOGICAL_TYPES", + "FLAG_STATIC_ENCODING", + "OPTION_STATIC_ENCODING", + "metadata", + "cachedFieldNames"); // Current attributes in Schema object. List currentAttributes = From 8ad2112bec9311ced41dfb79fdefb419854ad77b Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:43:39 -0800 Subject: [PATCH 02/15] Optimize built-in LogicalTypes with zero-copy Row construction and lookup caches Replaces Row.Builder allocations with zero-copy Row.attachValues, adds transient lookup/value caches on EnumerationType and OneOfType, replaces Math.pow with precomputed scaling tables in Timestamp, and removes redundant boxing across DateTime, FixedPrecisionNumeric, MicrosInstant, NanosInstant, NanosDuration, NanosType, and UuidLogicalType. --- .../sdk/schemas/logicaltypes/DateTime.java | 23 ++- .../schemas/logicaltypes/EnumerationType.java | 105 +++++++++-- .../logicaltypes/FixedPrecisionNumeric.java | 28 +-- .../schemas/logicaltypes/MicrosInstant.java | 15 +- .../schemas/logicaltypes/NanosDuration.java | 2 +- .../schemas/logicaltypes/NanosInstant.java | 2 +- .../sdk/schemas/logicaltypes/NanosType.java | 10 +- .../sdk/schemas/logicaltypes/OneOfType.java | 175 ++++++++++++++++-- .../sdk/schemas/logicaltypes/Timestamp.java | 137 +++++++++----- .../schemas/logicaltypes/UuidLogicalType.java | 19 +- 10 files changed, 407 insertions(+), 109 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java index 2659fc8644a7..26f86d22c94e 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/DateTime.java @@ -43,6 +43,7 @@ public class DateTime implements Schema.LogicalType { public static final String TIME_FIELD_NAME = "Time"; public static final Schema DATETIME_SCHEMA = Schema.builder().addInt64Field(DATE_FIELD_NAME).addInt64Field(TIME_FIELD_NAME).build(); + private static final Schema.FieldType BASE_TYPE = Schema.FieldType.row(DATETIME_SCHEMA); @Override public String getIdentifier() { @@ -63,26 +64,32 @@ public String getArgument() { @Override public Schema.FieldType getBaseType() { - return Schema.FieldType.row(DATETIME_SCHEMA); + return BASE_TYPE; } @Override public Row toBaseType(LocalDateTime input) { - return Row.withSchema(DATETIME_SCHEMA) - .addValues(input.toLocalDate().toEpochDay(), input.toLocalTime().toNanoOfDay()) - .build(); + return Row.attachValues( + DATETIME_SCHEMA, input.toLocalDate().toEpochDay(), input.toLocalTime().toNanoOfDay()); } @Override public LocalDateTime toInputType(Row base) { + Long date; + Long time; + if (DATETIME_SCHEMA.equals(base.getSchema())) { + date = base.getInt64(0); + time = base.getInt64(1); + } else { + date = base.getInt64(DATE_FIELD_NAME); + time = base.getInt64(TIME_FIELD_NAME); + } return LocalDateTime.of( LocalDate.ofEpochDay( checkArgumentNotNull( - base.getInt64(DATE_FIELD_NAME), - "While trying to convert to LocalDateTime: Row missing date field")), + date, "While trying to convert to LocalDateTime: Row missing date field")), LocalTime.ofNanoOfDay( checkArgumentNotNull( - base.getInt64(TIME_FIELD_NAME), - "While trying to convert to LocalDateTime: Row missing time field"))); + time, "While trying to convert to LocalDateTime: Row missing time field"))); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/EnumerationType.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/EnumerationType.java index d34ce7053b2e..e3578f0a9592 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/EnumerationType.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/EnumerationType.java @@ -17,15 +17,12 @@ */ package org.apache.beam.sdk.schemas.logicaltypes; -import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull; - import java.io.Serializable; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.beam.sdk.schemas.Schema.FieldType; @@ -33,13 +30,74 @@ import org.apache.beam.sdk.schemas.logicaltypes.EnumerationType.Value; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.BiMap; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableBiMap; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; import org.checkerframework.checker.nullness.qual.Nullable; /** This {@link LogicalType} represent an enumeration over a fixed set of values. */ public class EnumerationType implements LogicalType { public static final String IDENTIFIER = "Enum"; + private static final int MAX_DENSE_ENUM_VALUE = 256; + private static final FieldType ARGUMENT_TYPE = FieldType.map(FieldType.STRING, FieldType.INT32); + final BiMap enumValues; final List values; + private transient volatile @Nullable LookupCache lookupCache; + + private static final class LookupCache { + final ImmutableMap nameToValue; + final @Nullable Value @Nullable [] denseValues; + final @Nullable String @Nullable [] denseNames; + final @Nullable ImmutableMap sparseValues; + + LookupCache(BiMap enumValues) { + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + for (Integer v : enumValues.values()) { + int iv = v; + if (iv < min) { + min = iv; + } + if (iv > max) { + max = iv; + } + } + boolean useDense = + !enumValues.isEmpty() + && min >= 0 + && max <= MAX_DENSE_ENUM_VALUE + && max <= Math.max(enumValues.size() * 2, 64); + @Nullable Value @Nullable [] dVals = useDense ? new @Nullable Value[max + 1] : null; + @Nullable String @Nullable [] dNames = useDense ? new @Nullable String[max + 1] : null; + ImmutableMap.Builder byName = + ImmutableMap.builderWithExpectedSize(enumValues.size()); + ImmutableMap.Builder byId = + useDense ? null : ImmutableMap.builderWithExpectedSize(enumValues.size()); + for (Entry entry : enumValues.entrySet()) { + int id = entry.getValue(); + Value cached = new Value(id); + byName.put(entry.getKey(), cached); + if (dVals != null && dNames != null) { + dVals[id] = cached; + dNames[id] = entry.getKey(); + } else if (byId != null) { + byId.put(id, cached); + } + } + this.nameToValue = byName.build(); + this.denseValues = dVals; + this.denseNames = dNames; + this.sparseValues = byId != null ? byId.build() : null; + } + } + + private LookupCache getLookupCache() { + LookupCache cache = lookupCache; + if (cache == null) { + cache = new LookupCache(enumValues); + lookupCache = cache; + } + return cache; + } private EnumerationType(Map enumValues) { this.enumValues = ImmutableBiMap.copyOf(enumValues); @@ -48,6 +106,7 @@ private EnumerationType(Map enumValues) { .sorted(Comparator.comparingInt(e -> e.getValue())) .map(Entry::getKey) .collect(Collectors.toList()); + this.lookupCache = new LookupCache(this.enumValues); } /** Create an enumeration type over a set of String->Integer values. */ @@ -76,13 +135,29 @@ public static EnumerationType create(String... enumValues) { /** Return an {@link Value} corresponding to one of the enumeration strings. */ public Value valueOf(String stringValue) { - return new Value( - checkArgumentNotNull( - enumValues.get(stringValue), "Unknown enumeration value {}", stringValue)); + Value value = getLookupCache().nameToValue.get(stringValue); + if (value == null) { + throw new IllegalArgumentException( + String.format("Unknown enumeration value %s", stringValue)); + } + return value; } /** Return an {@link Value} corresponding to one of the enumeration integer values. */ public Value valueOf(int value) { + LookupCache cache = getLookupCache(); + @Nullable Value @Nullable [] dense = cache.denseValues; + if (dense != null && value >= 0 && value < dense.length) { + Value cached = dense[value]; + if (cached != null) { + return cached; + } + } else if (cache.sparseValues != null) { + Value cached = cache.sparseValues.get(value); + if (cached != null) { + return cached; + } + } return new Value(value); } @@ -93,7 +168,7 @@ public String getIdentifier() { @Override public FieldType getArgumentType() { - return FieldType.map(FieldType.STRING, FieldType.INT32); + return ARGUMENT_TYPE; } @Override @@ -121,6 +196,10 @@ public BiMap getValuesMap() { } public @Nullable String getEnumName(int number) { + @Nullable String @Nullable [] dense = getLookupCache().denseNames; + if (dense != null) { + return (number >= 0 && number < dense.length) ? dense[number] : null; + } return enumValues.inverse().get(number); } @@ -133,10 +212,12 @@ public List getValues() { } public String toString(EnumerationType.Value value) { - return checkArgumentNotNull( - enumValues.inverse().get(value.getValue()), - "Unknown enumeration value {}", - value.getValue()); + String name = getEnumName(value.getValue()); + if (name == null) { + throw new IllegalArgumentException( + String.format("Unknown enumeration value %s", value.getValue())); + } + return name; } @Override @@ -173,7 +254,7 @@ public boolean equals(@Nullable Object o) { @Override public int hashCode() { - return Objects.hash(value); + return 31 + value; } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/FixedPrecisionNumeric.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/FixedPrecisionNumeric.java index b089a58c5dd6..1857621ca918 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/FixedPrecisionNumeric.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/FixedPrecisionNumeric.java @@ -27,6 +27,7 @@ import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; /** Fixed precision numeric types used to represent jdbc NUMERIC and DECIMAL types. */ public class FixedPrecisionNumeric extends PassThroughLogicalType { @@ -57,6 +58,7 @@ public class FixedPrecisionNumeric extends PassThroughLogicalType { private final int precision; private final int scale; + private transient @Nullable MathContext mathContext; /** * Create a FixedPrecisionNumeric instance with specified precision and scale. ``precision=-1`` @@ -99,17 +101,21 @@ private FixedPrecisionNumeric(int precision, int scale) { @Override public BigDecimal toInputType(BigDecimal base) { - if (precision != -1) { - // check value not causing overflow when precision is fixed. - checkArgument( - base == null - || (base.precision() <= precision && base.scale() <= scale) - || base.round(new MathContext(precision)).compareTo(base) == 0, - "Expected BigDecimal base to be null or have precision <= %s (was %s), scale <= %s (was %s)", - precision, - (base == null) ? null : base.precision(), - scale, - (base == null) ? null : base.scale()); + if (precision != -1 && base != null) { + // Check value does not cause overflow when precision is fixed. + if (base.precision() > precision || base.scale() > scale) { + MathContext mc = mathContext; + if (mc == null) { + mc = new MathContext(precision); + mathContext = mc; + } + if (base.round(mc).compareTo(base) != 0) { + throw new IllegalArgumentException( + String.format( + "Expected BigDecimal base to be null or have precision <= %s (was %s), scale <= %s (was %s)", + precision, base.precision(), scale, base.scale())); + } + } } return base; } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/MicrosInstant.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/MicrosInstant.java index ec8d428bf517..cf14966e3eb0 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/MicrosInstant.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/MicrosInstant.java @@ -45,6 +45,7 @@ public class MicrosInstant implements Schema.LogicalType { .getExtension(RunnerApi.beamUrn); // TODO(https://github.com/apache/beam/issues/20540): This should be a constant private final Schema schema; + private transient volatile Schema.@Nullable FieldType cachedBaseType; public MicrosInstant() { this.schema = Schema.builder().addInt64Field("seconds").addInt32Field("micros").build(); @@ -52,12 +53,13 @@ public MicrosInstant() { @Override public Row toBaseType(Instant input) { - if (input.getNano() % 1000 != 0) { + int nano = input.getNano(); + if (nano % 1000 != 0) { throw new AssertionError( "micros_instant logical type encountered a Java " + "Instant with greater than microsecond precision."); } - return Row.withSchema(schema).addValues(input.getEpochSecond(), input.getNano() / 1000).build(); + return Row.attachValues(schema, input.getEpochSecond(), nano / 1000); } @Override @@ -67,7 +69,7 @@ public Instant toInputType(Row row) { row.getInt64(0), "While trying to convert to Instant: Row missing seconds field"), checkArgumentNotNull( row.getInt32(1), "While trying to convert to Instant: Row missing micros field") - * 1000); + * 1000L); } @Override @@ -82,6 +84,11 @@ public String getIdentifier() { @Override public Schema.FieldType getBaseType() { - return Schema.FieldType.row(schema); + Schema.FieldType baseType = cachedBaseType; + if (baseType == null) { + baseType = Schema.FieldType.row(schema); + cachedBaseType = baseType; + } + return baseType; } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosDuration.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosDuration.java index 07c58b40be87..55fa821458f6 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosDuration.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosDuration.java @@ -32,7 +32,7 @@ public NanosDuration() { @Override public Row toBaseType(Duration input) { - return Row.withSchema(schema).addValues(input.getSeconds(), input.getNano()).build(); + return Row.attachValues(schema, input.getSeconds(), input.getNano()); } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosInstant.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosInstant.java index f237ab2b1a43..f2be91b06e75 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosInstant.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosInstant.java @@ -32,7 +32,7 @@ public NanosInstant() { @Override public Row toBaseType(Instant input) { - return Row.withSchema(schema).addValues(input.getEpochSecond(), input.getNano()).build(); + return Row.attachValues(schema, input.getEpochSecond(), input.getNano()); } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosType.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosType.java index 9f06483a5aa5..032b22b80a5f 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosType.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/NanosType.java @@ -19,16 +19,19 @@ import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; /** Base class for types representing timestamps or durations as nanoseconds. */ abstract class NanosType implements Schema.LogicalType { private final String identifier; // TODO(https://github.com/apache/beam/issues/20540): This should be a constant protected final Schema schema; + private transient Schema.@Nullable FieldType cachedBaseType; NanosType(String identifier) { this.identifier = identifier; this.schema = Schema.builder().addInt64Field("seconds").addInt32Field("nanos").build(); + this.cachedBaseType = Schema.FieldType.row(this.schema); } @Override @@ -48,6 +51,11 @@ public String getArgument() { @Override public Schema.FieldType getBaseType() { - return Schema.FieldType.row(schema); + Schema.FieldType baseType = cachedBaseType; + if (baseType == null) { + baseType = Schema.FieldType.row(schema); + cachedBaseType = baseType; + } + return baseType; } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/OneOfType.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/OneOfType.java index 289d405d2ac3..96a75d523f5f 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/OneOfType.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/OneOfType.java @@ -17,10 +17,12 @@ */ package org.apache.beam.sdk.schemas.logicaltypes; -import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull; import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; +import java.math.BigDecimal; +import java.nio.ByteBuffer; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -33,6 +35,8 @@ import org.apache.beam.sdk.values.Row; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Instant; +import org.joda.time.ReadableInstant; /** * A logical type representing a union of fields. This logical type is initialized with a set of @@ -43,9 +47,89 @@ public class OneOfType implements LogicalType { public static final String IDENTIFIER = "OneOf"; + private static final int MAX_DENSE_CASE_VALUE = 256; + private final Schema oneOfSchema; private final EnumerationType enumerationType; private final byte[] schemaProtoRepresentation; + private transient volatile @Nullable LookupCache lookupCache; + + private static final class LookupCache { + final FieldType baseType; + final EnumerationType.Value[] fieldIndexToCase; + final FieldType[] fieldIndexToType; + final int @Nullable [] denseCaseToFieldIndex; + final @Nullable Map sparseCaseToFieldIndex; + + LookupCache(Schema oneOfSchema, EnumerationType enumerationType) { + int fieldCount = oneOfSchema.getFieldCount(); + this.baseType = FieldType.row(oneOfSchema); + this.fieldIndexToCase = new EnumerationType.Value[fieldCount]; + this.fieldIndexToType = new FieldType[fieldCount]; + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + for (int i = 0; i < fieldCount; i++) { + Field field = oneOfSchema.getField(i); + EnumerationType.Value caseVal = enumerationType.valueOf(field.getName()); + fieldIndexToCase[i] = caseVal; + fieldIndexToType[i] = field.getType(); + int iv = caseVal.getValue(); + if (iv < min) { + min = iv; + } + if (iv > max) { + max = iv; + } + } + boolean useDense = + fieldCount > 0 + && min >= 0 + && max <= MAX_DENSE_CASE_VALUE + && max <= Math.max(fieldCount * 2, 64); + if (useDense) { + int[] dense = new int[max + 1]; + Arrays.fill(dense, -1); + for (int i = 0; i < fieldCount; i++) { + dense[fieldIndexToCase[i].getValue()] = i; + } + this.denseCaseToFieldIndex = dense; + this.sparseCaseToFieldIndex = null; + } else { + Map sparse = new HashMap<>(fieldCount * 2); + for (int i = 0; i < fieldCount; i++) { + sparse.put(fieldIndexToCase[i].getValue(), i); + } + this.denseCaseToFieldIndex = null; + this.sparseCaseToFieldIndex = sparse; + } + } + + int getFieldIndex(int caseValue) { + if (denseCaseToFieldIndex != null) { + if (caseValue >= 0 && caseValue < denseCaseToFieldIndex.length) { + int idx = denseCaseToFieldIndex[caseValue]; + if (idx >= 0) { + return idx; + } + } + } else if (sparseCaseToFieldIndex != null) { + Integer idx = sparseCaseToFieldIndex.get(caseValue); + if (idx != null) { + return idx; + } + } + throw new IllegalArgumentException(String.format("Unknown enumeration value %s", caseValue)); + } + } + + private LookupCache getLookupCache() { + LookupCache cache = lookupCache; + if (cache == null) { + cache = new LookupCache(oneOfSchema, enumerationType); + lookupCache = cache; + } + return cache; + } private OneOfType(List fields) { this(fields, null); @@ -65,6 +149,7 @@ private OneOfType(List fields, @Nullable Map enumMap) { oneOfSchema = Schema.builder().addFields(nullableFields).build(); schemaProtoRepresentation = SchemaTranslation.schemaToProto(oneOfSchema, false, false).toByteArray(); + lookupCache = new LookupCache(oneOfSchema, enumerationType); } /** Create an {@link OneOfType} logical type. */ @@ -112,7 +197,7 @@ public byte[] getArgument() { @Override public FieldType getBaseType() { - return FieldType.row(oneOfSchema); + return getLookupCache().baseType; } /** Create a {@link Value} specifying which field to set and the value to set. */ @@ -131,35 +216,93 @@ public FieldType getBaseType() { } public FieldType getFieldType(OneOfType.Value oneOneValue) { - return oneOfSchema.getField(enumerationType.toString(oneOneValue.getCaseType())).getType(); + LookupCache cache = getLookupCache(); + return cache.fieldIndexToType[cache.getFieldIndex(oneOneValue.getCaseType().getValue())]; } @Override public Row toBaseType(Value input) { - EnumerationType.Value caseType = input.getCaseType(); - int setFieldIndex = oneOfSchema.indexOf(enumerationType.toString(caseType)); - Row.Builder builder = Row.withSchema(oneOfSchema); - for (int i = 0; i < oneOfSchema.getFieldCount(); ++i) { - Object value = (i == setFieldIndex) ? input.getValue() : null; - builder = builder.addValue(value); + LookupCache cache = getLookupCache(); + int setFieldIndex = cache.getFieldIndex(input.getCaseType().getValue()); + Object val = input.getValue(); + FieldType fieldType = cache.fieldIndexToType[setFieldIndex]; + @Nullable Object coerced = tryFastCoerceScalar(fieldType, val); + @Nullable Object[] values = new @Nullable Object[oneOfSchema.getFieldCount()]; + if (coerced != null) { + values[setFieldIndex] = coerced; + return Row.attachValues(oneOfSchema, values); + } + values[setFieldIndex] = val; + return Row.withSchema(oneOfSchema).addValues(Arrays.asList(values)).build(); + } + + private static @Nullable Object tryFastCoerceScalar(FieldType fieldType, @Nullable Object val) { + if (val == null) { + return null; + } + switch (fieldType.getTypeName()) { + case STRING: + return val instanceof String ? val : null; + case INT64: + return val instanceof Long ? val : null; + case INT32: + return val instanceof Integer ? val : null; + case DOUBLE: + return val instanceof Double ? val : null; + case FLOAT: + return val instanceof Float ? val : null; + case BOOLEAN: + return val instanceof Boolean ? val : null; + case BYTE: + return val instanceof Byte ? val : null; + case INT16: + return val instanceof Short ? val : null; + case DECIMAL: + return val instanceof BigDecimal ? val : null; + case BYTES: + if (val instanceof byte[]) { + return val; + } + if (val instanceof ByteBuffer) { + ByteBuffer bb = ((ByteBuffer) val).slice(); + byte[] bytes = new byte[bb.remaining()]; + bb.get(bytes); + return bytes; + } + return null; + case DATETIME: + if (val instanceof Instant) { + return val; + } + if (val instanceof ReadableInstant) { + return ((ReadableInstant) val).toInstant(); + } + return null; + default: + return null; } - return builder.build(); } @Override public Value toInputType(Row base) { + LookupCache cache = getLookupCache(); EnumerationType.Value caseType = null; Object oneOfValue = null; - for (int i = 0; i < base.getFieldCount(); ++i) { + int fieldCount = base.getFieldCount(); + for (int i = 0; i < fieldCount; ++i) { Object value = base.getValue(i); if (value != null) { - checkArgument(caseType == null, "More than one field set in union %s", this); - caseType = enumerationType.valueOf(oneOfSchema.getField(i).getName()); + if (caseType != null) { + throw new IllegalArgumentException( + String.format("More than one field set in union %s", this)); + } + caseType = cache.fieldIndexToCase[i]; oneOfValue = value; } } - checkArgumentNotNull(caseType, "No value set in union %s", this); - checkArgumentNotNull(oneOfValue, "No value set in union %s", this); + if (caseType == null || oneOfValue == null) { + throw new IllegalArgumentException(String.format("No value set in union %s", this)); + } return createValue(caseType, oneOfValue); } @@ -215,7 +358,7 @@ public boolean equals(@Nullable Object o) { @Override public int hashCode() { - return Objects.hash(caseType, value); + return 31 * (31 + Objects.hashCode(caseType)) + Objects.hashCode(value); } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/Timestamp.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/Timestamp.java index 51fa9008b749..e2dbc5f1b0c9 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/Timestamp.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/Timestamp.java @@ -17,9 +17,7 @@ */ package org.apache.beam.sdk.schemas.logicaltypes; -import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull; import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; -import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState; import java.time.Instant; import org.apache.beam.model.pipeline.v1.RunnerApi; @@ -27,6 +25,7 @@ import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.values.Row; import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; /** * A timestamp represented with configurable precision. @@ -67,17 +66,39 @@ public class Timestamp implements Schema.LogicalType { static final int MIN_PRECISION = 0; static final int MAX_PRECISION = 9; + private static final int[] SCALING_FACTORS = { + 1_000_000_000, 100_000_000, 10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10, 1 + }; + private static final int[] MAX_SUBSECONDS = { + 0, 9, 99, 999, 9_999, 99_999, 999_999, 9_999_999, 99_999_999, 999_999_999 + }; + private final int precision; private final int scalingFactor; private final Schema timestampSchema; + private transient volatile Schema.@Nullable FieldType cachedBaseType; + + private static final Timestamp[] INSTANCES = new Timestamp[MAX_PRECISION + 1]; + + static { + for (int i = MIN_PRECISION; i <= MAX_PRECISION; i++) { + INSTANCES[i] = new Timestamp(i); + } + } public static Timestamp of(int precision) { - return new Timestamp(precision); + if (precision < MIN_PRECISION || precision > MAX_PRECISION) { + throw new IllegalArgumentException( + String.format( + "Timestamp precision must be between %s and %s (inclusive), but was %s.", + MIN_PRECISION, MAX_PRECISION, precision)); + } + return INSTANCES[precision]; } - public static final Timestamp MILLIS = Timestamp.of(3); - public static final Timestamp MICROS = Timestamp.of(6); - public static final Timestamp NANOS = Timestamp.of(9); + public static final Timestamp MILLIS = INSTANCES[3]; + public static final Timestamp MICROS = INSTANCES[6]; + public static final Timestamp NANOS = INSTANCES[9]; public Timestamp(int precision) { checkArgument( @@ -87,7 +108,7 @@ public Timestamp(int precision) { MAX_PRECISION, precision); this.precision = precision; - this.scalingFactor = (int) Math.pow(10, MAX_PRECISION - precision); + this.scalingFactor = SCALING_FACTORS[precision]; if (precision < 5) { this.timestampSchema = Schema.builder().addInt64Field("seconds").addInt16Field("subseconds").build(); @@ -114,59 +135,77 @@ public Integer getArgument() { @Override public Schema.FieldType getBaseType() { - return Schema.FieldType.row(timestampSchema); + Schema.FieldType baseType = cachedBaseType; + if (baseType == null) { + baseType = Schema.FieldType.row(timestampSchema); + cachedBaseType = baseType; + } + return baseType; } @Override public Row toBaseType(Instant input) { - // Avoid silent data loss - checkState( - input.getNano() % scalingFactor == 0, - "Timestamp logical type was configured with precision %s, but encountered " - + "a Java Instant with %s nanoseconds (not evenly divisible by scaling factor %s).", - precision, - input.getNano(), - scalingFactor); - - int subseconds = input.getNano() / scalingFactor; - - Row.Builder rowBuilder = Row.withSchema(timestampSchema).addValue(input.getEpochSecond()); - if (precision < 5) { - rowBuilder.addValue((short) subseconds); // Explicitly add as short + int nano = input.getNano(); + int subseconds; + if (scalingFactor == 1) { + subseconds = nano; } else { - rowBuilder.addValue(subseconds); // Add as int + if (nano % scalingFactor != 0) { + throw new IllegalStateException( + String.format( + "Timestamp logical type was configured with precision %s, but encountered " + + "a Java Instant with %s nanoseconds (not evenly divisible by scaling factor %s).", + precision, nano, scalingFactor)); + } + subseconds = nano / scalingFactor; } - return rowBuilder.build(); + + if (precision < 5) { + return Row.attachValues(timestampSchema, input.getEpochSecond(), (short) subseconds); + } + return Row.attachValues(timestampSchema, input.getEpochSecond(), subseconds); } @Override public Instant toInputType(@NonNull Row base) { - long subseconds = - (precision < 5) - ? checkArgumentNotNull( - base.getInt16(1), - "While trying to convert to Instant: Row missing subseconds field") - : checkArgumentNotNull( - base.getInt32(1), - "While trying to convert to Instant: Row missing subseconds field"); + long subseconds; + if (precision < 5) { + Short s = base.getInt16(1); + if (s == null) { + throw new IllegalArgumentException( + "While trying to convert to Instant: Row missing subseconds field"); + } + subseconds = s; + } else { + Integer i = base.getInt32(1); + if (i == null) { + throw new IllegalArgumentException( + "While trying to convert to Instant: Row missing subseconds field"); + } + subseconds = i; + } - checkArgument( - subseconds >= 0, - "While trying to convert to Instant: subseconds field must be non-negative, " - + "but was %s. This likely indicates data corruption.", - subseconds); + if (subseconds < 0) { + throw new IllegalArgumentException( + String.format( + "While trying to convert to Instant: subseconds field must be non-negative, " + + "but was %s. This likely indicates data corruption.", + subseconds)); + } - int maxSubseconds = (int) (Math.pow(10, precision) - 1); - checkArgument( - subseconds <= maxSubseconds, - "While trying to convert to Instant: subseconds field must be <= %s for precision %s, " - + "but was %s. This likely indicates data corruption or precision mismatch.", - maxSubseconds, - precision, - subseconds); - return Instant.ofEpochSecond( - checkArgumentNotNull( - base.getInt64(0), "While trying to convert to Instant: Row missing seconds field"), - subseconds * scalingFactor); + int maxSubseconds = MAX_SUBSECONDS[precision]; + if (subseconds > maxSubseconds) { + throw new IllegalArgumentException( + String.format( + "While trying to convert to Instant: subseconds field must be <= %s for precision %s, " + + "but was %s. This likely indicates data corruption or precision mismatch.", + maxSubseconds, precision, subseconds)); + } + Long seconds = base.getInt64(0); + if (seconds == null) { + throw new IllegalArgumentException( + "While trying to convert to Instant: Row missing seconds field"); + } + return Instant.ofEpochSecond(seconds, subseconds * scalingFactor); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/UuidLogicalType.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/UuidLogicalType.java index dfd17e752d3e..db669fc6e14f 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/UuidLogicalType.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/UuidLogicalType.java @@ -32,6 +32,7 @@ public class UuidLogicalType implements Schema.LogicalType { .addInt64Field(MOST_SIGNIFICANT_BITS_FIELD_NAME) .addInt64Field(LEAST_SIGNIFICANT_BITS_FIELD_NAME) .build(); + private static final FieldType BASE_TYPE = Schema.FieldType.row(UUID_SCHEMA); @Override public String getIdentifier() { @@ -52,20 +53,26 @@ public String getArgument() { @Override public FieldType getBaseType() { - return Schema.FieldType.row(UUID_SCHEMA); + return BASE_TYPE; } @Override public Row toBaseType(UUID input) { - return Row.withSchema(UUID_SCHEMA) - .addValues(input.getMostSignificantBits(), input.getLeastSignificantBits()) - .build(); + return Row.attachValues( + UUID_SCHEMA, input.getMostSignificantBits(), input.getLeastSignificantBits()); } @Override public UUID toInputType(Row base) { - Long leastSignificantBitsValue = base.getInt64(LEAST_SIGNIFICANT_BITS_FIELD_NAME); - Long mostSignificantBitsValue = base.getInt64(MOST_SIGNIFICANT_BITS_FIELD_NAME); + Long mostSignificantBitsValue; + Long leastSignificantBitsValue; + if (UUID_SCHEMA.equals(base.getSchema())) { + mostSignificantBitsValue = base.getInt64(0); + leastSignificantBitsValue = base.getInt64(1); + } else { + leastSignificantBitsValue = base.getInt64(LEAST_SIGNIFICANT_BITS_FIELD_NAME); + mostSignificantBitsValue = base.getInt64(MOST_SIGNIFICANT_BITS_FIELD_NAME); + } if (leastSignificantBitsValue == null || mostSignificantBitsValue == null) { throw new IllegalStateException( String.format( From 4ca8adca7728d1345aafc0d490d0eba8f48e0f3c Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:44:55 -0800 Subject: [PATCH 03/15] Optimize ByteBuddy accessors, creators, and GetterBasedSchemaProvider Eliminates reflection, redundant container copies, double getter evaluation, and LogicalType triple round-trips in ByteBuddy codegen and schema providers: - ByteBuddyUtils: elides identity container/map Function wrappers and TransformingMap copies, caches singleton Function instances and Enum.values(), spills IfNullElse values to avoid double getter evaluation, uses ClassValue-anchored caches, and fast-paths primitive arrays. - JavaBeanUtils / SetterBasedCreatorFactory / JavaBeanSchema: adds cached ByteBuddy setter-based JavaBean creator (falling back safely to reflection with hoisted Constructor/FieldValueSetter[]). - POJOUtils: chunks >128-field POJO creators into 64-field setChunk helpers with generation-time zero-arg constructor validation. - GetterBasedSchemaProvider / FromRowUsingCreator / CachingFactory: eliminates LogicalType toBaseType/toInputType round-trips, avoids per-row CHM/Optional/identity-converter overhead, and adds monomorphic CachingFactory fast slot. - AutoValueUtils / ConvertHelpers / ReflectUtils: adds ClassValue-anchored codegen caches and reuses DefaultTypeConversionsFactory.INSTANCE. --- .../beam/sdk/schemas/AutoValueSchema.java | 4 +- .../beam/sdk/schemas/CachingFactory.java | 44 +- .../beam/sdk/schemas/FromRowUsingCreator.java | 206 +++++-- .../schemas/GetterBasedSchemaProvider.java | 162 +++++- .../beam/sdk/schemas/JavaBeanSchema.java | 27 +- .../beam/sdk/schemas/JavaFieldSchema.java | 8 +- .../schemas/SetterBasedCreatorFactory.java | 61 +- .../sdk/schemas/utils/AutoValueUtils.java | 64 ++ .../sdk/schemas/utils/ByteBuddyUtils.java | 548 +++++++++++++----- .../sdk/schemas/utils/ConvertHelpers.java | 66 ++- .../beam/sdk/schemas/utils/JavaBeanUtils.java | 434 +++++++++++++- .../beam/sdk/schemas/utils/POJOUtils.java | 197 ++++++- .../beam/sdk/schemas/utils/ReflectUtils.java | 62 +- 13 files changed, 1573 insertions(+), 310 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/AutoValueSchema.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/AutoValueSchema.java index 49eebe13af58..5ac570184c35 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/AutoValueSchema.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/AutoValueSchema.java @@ -93,7 +93,7 @@ private static void validateFieldNumbers(List types) targetTypeDescriptor, schema, AbstractGetterTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } @Override @@ -114,7 +114,7 @@ public SchemaUserTypeCreator schemaTypeCreator( annotated, schema, AbstractGetterTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } // Try to find a generated builder class. If one exists, use that to generate a diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/CachingFactory.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/CachingFactory.java index c8c67931ec27..b6b2c8aba99f 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/CachingFactory.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/CachingFactory.java @@ -17,6 +17,7 @@ */ package org.apache.beam.sdk.schemas; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import org.apache.beam.sdk.values.TypeDescriptor; @@ -37,9 +38,26 @@ * inner factory, so the schema comparison only need happen on the first lookup. */ public class CachingFactory implements Factory { + private static final class CachedEntry { + final @Nullable TypeDescriptor key; + final @Nullable T value; + + CachedEntry(@Nullable TypeDescriptor key, @Nullable T value) { + this.key = key; + this.value = value; + } + } + + // Sentinel written once if this CachingFactory observes more than one TypeDescriptor, disabling + // the monomorphic fast slot so polymorphic callers do zero allocations and zero volatile writes. + private static final CachedEntry POLYMORPHIC = new CachedEntry<>(null, null); + private transient volatile @MonotonicNonNull ConcurrentHashMap, CreatedT> cache = null; + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") + private transient volatile @Nullable CachedEntry lastEntry = null; + private final @NotOnlyInitialized Factory innerFactory; public CachingFactory(@UnknownInitialization Factory innerFactory) { @@ -60,15 +78,35 @@ private ConcurrentHashMap, CreatedT> getCache() { } @Override + @SuppressWarnings({"ReferenceEquality", "unchecked"}) public CreatedT create(TypeDescriptor typeDescriptor, Schema schema) { + CachedEntry fast = lastEntry; + if (fast != null && fast != POLYMORPHIC) { + TypeDescriptor k = fast.key; + CreatedT v = fast.value; + if (k != null && v != null && (k == typeDescriptor || k.equals(typeDescriptor))) { + return v; + } + } ConcurrentHashMap, CreatedT> cache = getCache(); CreatedT cached = cache.get(typeDescriptor); if (cached != null) { + if (fast == null) { + lastEntry = new CachedEntry<>(typeDescriptor, cached); + } else if (fast != POLYMORPHIC) { + lastEntry = (CachedEntry) POLYMORPHIC; + } return cached; } - cached = innerFactory.create(typeDescriptor, schema); - cache.put(typeDescriptor, cached); - return cached; + CreatedT created = innerFactory.create(typeDescriptor, schema); + CreatedT existing = cache.putIfAbsent(typeDescriptor, created); + CreatedT result = existing != null ? existing : created; + if (fast == null) { + lastEntry = new CachedEntry<>(typeDescriptor, result); + } else if (fast != POLYMORPHIC) { + lastEntry = (CachedEntry) POLYMORPHIC; + } + return result; } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FromRowUsingCreator.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FromRowUsingCreator.java index 0f5c47f72591..fcebd46696d7 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FromRowUsingCreator.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/FromRowUsingCreator.java @@ -30,9 +30,11 @@ import org.apache.beam.sdk.schemas.Schema.TypeName; import org.apache.beam.sdk.schemas.logicaltypes.EnumerationType; import org.apache.beam.sdk.schemas.logicaltypes.OneOfType; +import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.RowWithGetters; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.sdk.values.TypeDescriptor; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Function; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Collections2; @@ -52,8 +54,21 @@ class FromRowUsingCreator implements SerializableFunction, Function schemaTypeCreatorFactory; + private static final class ConverterPlan { + final @Nullable Function[] fieldConverters; + final boolean hasConversions; + + ConverterPlan(@Nullable Function[] fieldConverters, boolean hasConversions) { + this.fieldConverters = fieldConverters; + this.hasConversions = hasConversions; + } + } + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") - private transient volatile @MonotonicNonNull Function[] fieldConverters; + private transient volatile @MonotonicNonNull ConverterPlan converterPlan; + + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") + private transient volatile @MonotonicNonNull SchemaUserTypeCreator cachedCreator; public FromRowUsingCreator( TypeDescriptor typeDescriptor, GetterBasedSchemaProvider schemaProvider) { @@ -68,49 +83,85 @@ private FromRowUsingCreator( TypeDescriptor typeDescriptor, GetterBasedSchemaProvider schemaProvider, Factory schemaTypeCreatorFactory, - @Nullable Function[] fieldConverters) { + @Nullable ConverterPlan converterPlan) { this.typeDescriptor = typeDescriptor; this.schemaProvider = schemaProvider; this.schemaTypeCreatorFactory = schemaTypeCreatorFactory; - this.fieldConverters = fieldConverters; + this.converterPlan = converterPlan; } @Override - @SuppressWarnings("unchecked") + @SuppressWarnings({"unchecked", "ReferenceEquality"}) public T apply(Row row) { if (row == null) { return null; } if (row instanceof RowWithGetters) { RowWithGetters rowWithGetters = (RowWithGetters) row; - if (rowWithGetters.getGetterTargetType().equals(typeDescriptor)) { + TypeDescriptor targetType = rowWithGetters.getGetterTargetType(); + if (targetType == typeDescriptor || targetType.equals(typeDescriptor)) { // Efficient path: simply extract the underlying object instead of creating a new one. return (T) rowWithGetters.getGetterTarget(); } } - if (fieldConverters == null) { - initFieldConverters(row.getSchema()); + Schema rowSchema = row.getSchema(); + ConverterPlan plan = this.converterPlan; + if (plan == null) { + plan = initFieldConverters(rowSchema); + } + @Nullable Function[] converters = plan.fieldConverters; + int fieldCount = row.getFieldCount(); + checkState(converters.length == fieldCount, "Unexpected field count"); + + SchemaUserTypeCreator creator = this.cachedCreator; + if (creator == null) { + creator = schemaTypeCreatorFactory.create(typeDescriptor, rowSchema); + this.cachedCreator = creator; } - checkState(fieldConverters.length == row.getFieldCount(), "Unexpected field count"); - Object[] params = new Object[row.getFieldCount()]; - for (int i = 0; i < row.getFieldCount(); ++i) { - params[i] = fieldConverters[i].apply(row.getValue(i)); + if (row instanceof RowWithStorage) { + @Nullable Object[] rawArr = ((RowWithStorage) row).getRawArray(); + if (rawArr != null) { + if (!plan.hasConversions) { + return (T) creator.create(rawArr); + } + Object[] params = new Object[fieldCount]; + for (int i = 0; i < fieldCount; ++i) { + Function converter = converters[i]; + Object val = rawArr[i]; + params[i] = converter != null ? converter.apply(val) : val; + } + return (T) creator.create(params); + } + } + + Object[] params = new Object[fieldCount]; + if (!plan.hasConversions) { + for (int i = 0; i < fieldCount; ++i) { + params[i] = row.getValue(i); + } + } else { + for (int i = 0; i < fieldCount; ++i) { + Function converter = converters[i]; + Object val = row.getValue(i); + params[i] = converter != null ? converter.apply(val) : val; + } } - SchemaUserTypeCreator creator = - schemaTypeCreatorFactory.create(typeDescriptor, row.getSchema()); return (T) creator.create(params); } - private synchronized void initFieldConverters(Schema schema) { - if (fieldConverters == null) { + private synchronized ConverterPlan initFieldConverters(Schema schema) { + ConverterPlan plan = this.converterPlan; + if (plan == null) { CachingFactory> typeFactory = new CachingFactory<>(schemaProvider::fieldValueTypeInformations); - fieldConverters = fieldConverters(typeDescriptor, schema, typeFactory); + plan = fieldConverters(typeDescriptor, schema, typeFactory); + this.converterPlan = plan; } + return plan; } - private Function[] fieldConverters( + private ConverterPlan fieldConverters( TypeDescriptor typeDescriptor, Schema schema, Factory> typeFactory) { @@ -118,11 +169,17 @@ private Function[] fieldConverters( checkState( typeInfos.size() == schema.getFieldCount(), "Did not have a matching number of type informations and fields."); - Function[] converters = new Function[schema.getFieldCount()]; + @Nullable Function[] converters = new Function[schema.getFieldCount()]; + boolean hasConversions = false; for (int i = 0; i < converters.length; i++) { - converters[i] = fieldConverter(schema.getField(i).getType(), typeInfos.get(i), typeFactory); + Function converter = + fieldConverter(schema.getField(i).getType(), typeInfos.get(i), typeFactory); + converters[i] = converter; + if (converter != null) { + hasConversions = true; + } } - return converters; + return new ConverterPlan(converters, hasConversions); } private static boolean needsConversion(FieldType type) { @@ -135,26 +192,34 @@ && needsConversion(type.getCollectionElementType())) && (needsConversion(type.getMapKeyType()) || needsConversion(type.getMapValueType()))); } - private Function fieldConverter( + /** Returns a converter for the given field type, or {@code null} when identity suffices. */ + private @Nullable Function fieldConverter( FieldType type, FieldValueTypeInformation typeInfo, Factory> typeFactory) { if (!needsConversion(type)) { - return FieldConverter.IDENTITY; + return null; } else if (TypeName.ROW.equals(type.getTypeName())) { - Function[] converters = fieldConverters(typeInfo.getType(), type.getRowSchema(), typeFactory); + ConverterPlan nestedPlan = + fieldConverters(typeInfo.getType(), type.getRowSchema(), typeFactory); return new FromRowUsingCreator( - typeInfo.getType(), schemaProvider, schemaTypeCreatorFactory, converters); + typeInfo.getType(), schemaProvider, schemaTypeCreatorFactory, nestedPlan); } else if (TypeName.ARRAY.equals(type.getTypeName())) { - return new ConvertCollection( - fieldConverter(type.getCollectionElementType(), typeInfo.getElementType(), typeFactory)); + Function elementConverter = + fieldConverter(type.getCollectionElementType(), typeInfo.getElementType(), typeFactory); + return elementConverter == null ? null : new ConvertCollection(elementConverter); } else if (TypeName.ITERABLE.equals(type.getTypeName())) { - return new ConvertIterable( - fieldConverter(type.getCollectionElementType(), typeInfo.getElementType(), typeFactory)); + Function elementConverter = + fieldConverter(type.getCollectionElementType(), typeInfo.getElementType(), typeFactory); + return elementConverter == null ? null : new ConvertIterable(elementConverter); } else if (TypeName.MAP.equals(type.getTypeName())) { - return new ConvertMap( - fieldConverter(type.getMapKeyType(), typeInfo.getMapKeyType(), typeFactory), - fieldConverter(type.getMapValueType(), typeInfo.getMapValueType(), typeFactory)); + Function keyConverter = + fieldConverter(type.getMapKeyType(), typeInfo.getMapKeyType(), typeFactory); + Function valueConverter = + fieldConverter(type.getMapValueType(), typeInfo.getMapValueType(), typeFactory); + return (keyConverter == null && valueConverter == null) + ? null + : new ConvertMap(keyConverter, valueConverter); } else if (type.isLogicalType(OneOfType.IDENTIFIER)) { OneOfType oneOfType = type.getLogicalType(OneOfType.class); Schema schema = oneOfType.getOneOfSchema(); @@ -167,13 +232,24 @@ private Function fieldConverter( FieldType caseType = schema.getField(name).getType(); FieldValueTypeInformation caseTypeInfo = checkNotNull(typeInfo.getOneOfTypes().get(name)); - readers.put(id, fieldConverter(caseType, caseTypeInfo, typeFactory)); + Function converter = fieldConverter(caseType, caseTypeInfo, typeFactory); + readers.put(id, converter == null ? FieldConverter.IDENTITY : converter); }); return new ConvertOneOf(oneOfType, readers); } else if (type.getTypeName().isLogicalType()) { + Class providerClass = schemaProvider.getClass(); + if ((providerClass == JavaFieldSchema.class + || providerClass == JavaBeanSchema.class + || providerClass == AutoValueSchema.class) + && ByteBuddyUtils.matchesInferredLogicalType( + type.getLogicalType(), typeInfo.getRawType())) { + // Generated setters accept the Java input type directly via convertLogicalTypeForSetter, + // avoiding the toBaseType -> toInputType round-trip allocation. + return null; + } return new ConvertLogicalType<>(type.getLogicalType()); } - return FieldConverter.IDENTITY; + return null; } private interface FieldConverter @@ -222,37 +298,81 @@ public Iterable convert(Iterable iterable) { } private static class ConvertMap implements FieldConverter { - final Function keyConverter, valueConverter; + final @Nullable Function keyConverter; + final @Nullable Function valueConverter; - ConvertMap(Function keyConverter, Function valueConverter) { + ConvertMap(@Nullable Function keyConverter, @Nullable Function valueConverter) { this.keyConverter = keyConverter; this.valueConverter = valueConverter; } @Override + @SuppressWarnings("unchecked") public Map convert(Map field) { + if (keyConverter == null && valueConverter == null) { + return field; + } Map result = Maps.newHashMapWithExpectedSize(field.size()); - field.forEach((k, v) -> result.put(keyConverter.apply(k), valueConverter.apply(v))); + for (Map.Entry entry : ((Map) field).entrySet()) { + Object k = entry.getKey(); + Object v = entry.getValue(); + result.put( + keyConverter != null ? keyConverter.apply(k) : k, + valueConverter != null ? valueConverter.apply(v) : v); + } return result; } } private static class ConvertOneOf implements FieldConverter { + private static final int MAX_DENSE_ENUM_ID = 256; final OneOfType oneOfType; final Map converters; + final @Nullable Function @Nullable [] denseConverters; ConvertOneOf(OneOfType oneOfType, Map converters) { this.oneOfType = oneOfType; this.converters = converters; + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + for (Integer id : converters.keySet()) { + int v = id; + if (v < min) { + min = v; + } + if (v > max) { + max = v; + } + } + if (min >= 0 && max >= 0 && max < MAX_DENSE_ENUM_ID && !converters.isEmpty()) { + Function[] dense = new Function[max + 1]; + for (Map.Entry entry : converters.entrySet()) { + dense[entry.getKey()] = entry.getValue(); + } + this.denseConverters = dense; + } else { + this.denseConverters = null; + } } @Override public OneOfType.Value convert(OneOfType.Value field) { EnumerationType.Value caseType = field.getCaseType(); + int id = caseType.getValue(); Function converter = - checkStateNotNull( - converters.get(caseType.getValue()), "Missing OneOf converter for case %s."); - return oneOfType.createValue(caseType, converter.apply(field.getValue())); + denseConverters != null + ? (id >= 0 && id < denseConverters.length ? denseConverters[id] : null) + : converters.get(id); + checkStateNotNull(converter, "Missing OneOf converter for case %s.", caseType); + if (converter == FieldConverter.IDENTITY) { + return field; + } + Object rawValue = field.getValue(); + Object converted = converter.apply(rawValue); + if (converted == rawValue) { + return field; + } + return oneOfType.createValue(caseType, converted); } } @@ -270,6 +390,14 @@ public ValueT convert(FieldT field) { } } + TypeDescriptor getTypeDescriptor() { + return typeDescriptor; + } + + GetterBasedSchemaProvider getSchemaProvider() { + return schemaProvider; + } + @Override public boolean equals(@Nullable Object o) { if (this == o) { diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/GetterBasedSchemaProvider.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/GetterBasedSchemaProvider.java index 0743551781da..4bd16c7f7cff 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/GetterBasedSchemaProvider.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/GetterBasedSchemaProvider.java @@ -19,6 +19,7 @@ import static org.apache.beam.sdk.util.Preconditions.checkStateNotNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -33,6 +34,7 @@ import org.apache.beam.sdk.schemas.Schema.TypeName; import org.apache.beam.sdk.schemas.logicaltypes.EnumerationType; import org.apache.beam.sdk.schemas.logicaltypes.OneOfType; +import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils; import org.apache.beam.sdk.schemas.utils.ReflectUtils; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.Row; @@ -117,12 +119,14 @@ public SchemaUserTypeCreator schemaTypeCreator( return schemaTypeCreator(targetTypeDescriptor.getRawType(), schema); } - private class ToRowWithValueGetters - implements SerializableFunction { + class ToRowWithValueGetters implements SerializableFunction { private final Schema schema; private final Factory>> getterFactory; private final TypeDescriptor getterTargetType; + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") + private transient volatile @Nullable List> cachedGetters; + public ToRowWithValueGetters(Schema schema, TypeDescriptor getterTargetType) { this.schema = schema; this.getterTargetType = getterTargetType; @@ -140,13 +144,26 @@ public ToRowWithValueGetters(Schema schema, TypeDescriptor getterTargetType) { @Override public Row apply(T input) { - return Row.withSchema(schema).withFieldValueGetters(getterFactory, input, getterTargetType); + List> getters = cachedGetters; + if (getters == null) { + getters = getterFactory.create(getterTargetType, schema); + cachedGetters = getters; + } + return Row.withFieldValueGetters(schema, getters, input, getterTargetType); } - private GetterBasedSchemaProvider getOuter() { + GetterBasedSchemaProvider getOuter() { return GetterBasedSchemaProvider.this; } + Schema getSchema() { + return schema; + } + + TypeDescriptor getTargetType() { + return getterTargetType; + } + @Override public boolean equals(@Nullable Object o) { if (this == o) { @@ -187,7 +204,7 @@ public SerializableFunction fromRowFunction(TypeDescriptor typeDe @Override public int hashCode() { - return super.hashCode(); + return getClass().hashCode(); } @Override @@ -304,7 +321,14 @@ FieldValueGetter rowValueGetter( return new GetOneOf(base, converters, oneOfType); } else if (typeName.isLogicalType()) { - return new GetLogicalInputType(base, Verify.verifyNotNull(type.getLogicalType())); + LogicalType logicalType = Verify.verifyNotNull(type.getLogicalType()); + if (base instanceof ByteBuddyUtils.DirectLogicalTypeGetter + && getterReturnType != null + && ByteBuddyUtils.matchesInferredLogicalType( + logicalType, getterReturnType.getRawType())) { + return new GetRawPassThrough<>(base); + } + return new GetLogicalInputType(base, logicalType); } return base; } @@ -318,6 +342,7 @@ static class GetRow final Schema schema; final Factory>> factory; final @Nullable TypeDescriptor valueType; + transient volatile @Nullable List> cachedGetters; GetRow( FieldValueGetter getter, @@ -332,12 +357,17 @@ static class GetRow @Override Object convert(V value) { - return Row.withSchema(schema) - .withFieldValueGetters( - factory, - value, - Optional.ofNullable(valueType) - .orElse((TypeDescriptor) TypeDescriptor.of(value.getClass()))); + TypeDescriptor typeDescriptor = valueType; + if (typeDescriptor != null) { + List> getters = cachedGetters; + if (getters == null) { + getters = factory.create(typeDescriptor, schema); + cachedGetters = getters; + } + return Row.withFieldValueGetters(schema, getters, value, typeDescriptor); + } + return Row.withFieldValueGetters( + schema, factory, value, TypeDescriptor.of(value.getClass())); } } @@ -360,11 +390,12 @@ Object convert(Collection collection) { } static class GetCollection extends Converter { - final FieldValueGetter converter; + final org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Function convertFn; + @SuppressWarnings("nullness") GetCollection(FieldValueGetter getter, FieldValueGetter converter) { super(getter); - this.converter = converter; + this.convertFn = converter::get; } @Override @@ -374,25 +405,26 @@ Object convert(Collection collection) { // For performance reasons if the input is a list, make sure that we produce a list. // Otherwise, Row forwarding is forced to physically copy the collection into a new List // object. - return Lists.transform((List) collection, converter::get); + return Lists.transform((List) collection, convertFn); } else { - return Collections2.transform(collection, converter::get); + return Collections2.transform(collection, convertFn); } } } static class GetIterable extends Converter { - final FieldValueGetter converter; + final org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Function convertFn; + @SuppressWarnings("nullness") GetIterable(FieldValueGetter getter, FieldValueGetter converter) { super(getter); - this.converter = converter; + this.convertFn = converter::get; } @Override @SuppressWarnings({"nullness"}) Object convert(Iterable value) { - return Iterables.transform(value, converter::get); + return Iterables.transform(value, convertFn); } } @@ -400,6 +432,8 @@ static class GetMap extends Converter> { final FieldValueGetter<@NonNull K1, K2> keyConverter; final FieldValueGetter<@NonNull V1, V2> valueConverter; + final boolean convertKey; + final boolean convertValue; GetMap( FieldValueGetter> getter, @@ -408,20 +442,52 @@ static class GetMap super(getter); this.keyConverter = keyConverter; this.valueConverter = valueConverter; + this.convertKey = keyConverter != IDENTITY; + this.convertValue = valueConverter != IDENTITY; } @Override + @SuppressWarnings("unchecked") Map<@Nullable K2, @Nullable V2> convert(Map<@Nullable K1, @Nullable V1> value) { + if (!convertKey && !convertValue) { + return (Map<@Nullable K2, @Nullable V2>) value; + } Map<@Nullable K2, @Nullable V2> returnMap = Maps.newHashMapWithExpectedSize(value.size()); for (Map.Entry<@Nullable K1, @Nullable V1> entry : value.entrySet()) { - returnMap.put( - Optional.ofNullable(entry.getKey()).map(keyConverter::get).orElse(null), - Optional.ofNullable(entry.getValue()).map(valueConverter::get).orElse(null)); + @Nullable K1 k = entry.getKey(); + @Nullable V1 v = entry.getValue(); + @Nullable K2 outKey = (k == null || !convertKey) ? (K2) k : keyConverter.get(k); + @Nullable V2 outValue = (v == null || !convertValue) ? (V2) v : valueConverter.get(v); + returnMap.put(outKey, outValue); } return returnMap; } } + static class GetRawPassThrough + implements FieldValueGetter { + final FieldValueGetter getter; + + GetRawPassThrough(FieldValueGetter getter) { + this.getter = getter; + } + + @Override + public @Nullable Object get(T object) { + return getter.getRaw(object); + } + + @Override + public @Nullable Object getRaw(T object) { + return getter.getRaw(object); + } + + @Override + public String name() { + return getter.name(); + } + } + static class GetLogicalInputType extends Converter { final LogicalType logicalType; @@ -438,9 +504,12 @@ Object convert(Object value) { } static class GetOneOf extends Converter { + private static final int MAX_DENSE_ENUM_ID = 256; final OneOfType oneOfType; final Map> converters; + final @Nullable FieldValueGetter<@NonNull Object, Object> @Nullable [] denseConverters; + @SuppressWarnings({"unchecked", "rawtypes"}) GetOneOf( FieldValueGetter getter, Map> converters, @@ -448,23 +517,54 @@ static class GetOneOf extends Converter max) { + max = v; + } + } + if (min >= 0 && max >= 0 && max < MAX_DENSE_ENUM_ID && !converters.isEmpty()) { + @Nullable FieldValueGetter<@NonNull Object, Object>[] dense = + new FieldValueGetter[max + 1]; + for (Map.Entry> entry : + converters.entrySet()) { + dense[entry.getKey()] = entry.getValue(); + } + this.denseConverters = dense; + } else { + this.denseConverters = null; + } } @Override Object convert(OneOfType.Value value) { EnumerationType.Value caseType = value.getCaseType(); - - @NonNull FieldValueGetter<@NonNull Object, Object> converter = - checkStateNotNull( - converters.get(caseType.getValue()), - "Missing OneOf converter for case %s.", - caseType); - + int id = caseType.getValue(); + @Nullable FieldValueGetter<@NonNull Object, Object> converter; + @Nullable FieldValueGetter<@NonNull Object, Object> @Nullable [] dense = denseConverters; + if (dense != null) { + converter = (id >= 0 && id < dense.length) ? dense[id] : null; + } else { + converter = converters.get(id); + } + @NonNull FieldValueGetter<@NonNull Object, Object> nonNullConverter = + checkStateNotNull(converter, "Missing OneOf converter for case %s.", caseType); + Object rawValue = value.getValue(); + if (nonNullConverter == IDENTITY) { + return value; + } Object convertedValue = checkStateNotNull( - converter.get(value.getValue()), + nonNullConverter.get(rawValue), "Bug! converting a non-null value in a OneOf resulted in null result value"); - + if (convertedValue == rawValue) { + return value; + } return oneOfType.createValue(caseType, convertedValue); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaBeanSchema.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaBeanSchema.java index 7d0b3a6175c9..c884415848fe 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaBeanSchema.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaBeanSchema.java @@ -90,7 +90,7 @@ private static void validateFieldNumbers(List types) @Override public int hashCode() { - return System.identityHashCode(this); + return GetterTypeSupplier.class.hashCode(); } @Override @@ -102,7 +102,7 @@ public boolean equals(@Nullable Object obj) { /** {@link FieldValueTypeSupplier} that's based on setter methods. */ @VisibleForTesting public static class SetterTypeSupplier implements FieldValueTypeSupplier { - private static final SetterTypeSupplier INSTANCE = new SetterTypeSupplier(); + static final SetterTypeSupplier INSTANCE = new SetterTypeSupplier(); @Override public List get(TypeDescriptor typeDescriptor) { @@ -143,7 +143,7 @@ public List get(TypeDescriptor typeDescriptor) { @Override public int hashCode() { - return System.identityHashCode(this); + return SetterTypeSupplier.class.hashCode(); } @Override @@ -176,7 +176,7 @@ public Schema schemaFor(TypeDescriptor typeDescriptor) { targetTypeDescriptor, schema, GetterTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } @Override @@ -196,7 +196,7 @@ public SchemaUserTypeCreator schemaTypeCreator( annotated, schema, GetterTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } // If a Constructor was tagged with @SchemaCreate, invoke that constructor. @@ -208,10 +208,19 @@ public SchemaUserTypeCreator schemaTypeCreator( constructor, schema, GetterTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } - // Else try to make a setter-based creator + // Else try to use a cached ByteBuddy setter-based creator, falling back to reflection. + @Nullable SchemaUserTypeCreator generatedCreator = + JavaBeanUtils.getSetterCreator( + targetTypeDescriptor, + schema, + SetterTypeSupplier.INSTANCE, + DefaultTypeConversionsFactory.INSTANCE); + if (generatedCreator != null) { + return generatedCreator; + } Factory setterBasedFactory = new SetterBasedCreatorFactory(new JavaBeanSetterFactory()); return setterBasedFactory.create(targetTypeDescriptor, schema); @@ -225,13 +234,13 @@ public List create(TypeDescriptor targetTypeDescriptor, Sch targetTypeDescriptor, schema, SetterTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } } @Override public int hashCode() { - return System.identityHashCode(this); + return JavaBeanSchema.class.hashCode(); } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaFieldSchema.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaFieldSchema.java index 3e0c9c879201..c5a58798ca12 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaFieldSchema.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/JavaFieldSchema.java @@ -122,7 +122,7 @@ public Schema schemaFor(TypeDescriptor typeDescriptor) { targetTypeDescriptor, schema, JavaFieldTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } @Override @@ -142,7 +142,7 @@ public SchemaUserTypeCreator schemaTypeCreator( annotated, schema, JavaFieldTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } // If a Constructor was tagged with @SchemaCreate, invoke that constructor. @@ -154,13 +154,13 @@ public SchemaUserTypeCreator schemaTypeCreator( constructor, schema, JavaFieldTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } return POJOUtils.getSetFieldCreator( targetTypeDescriptor, schema, JavaFieldTypeSupplier.INSTANCE, - new DefaultTypeConversionsFactory()); + DefaultTypeConversionsFactory.INSTANCE); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SetterBasedCreatorFactory.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SetterBasedCreatorFactory.java index e7ded3c52af5..8f057564c2b5 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SetterBasedCreatorFactory.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SetterBasedCreatorFactory.java @@ -17,9 +17,11 @@ */ package org.apache.beam.sdk.schemas; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.apache.beam.sdk.values.TypeDescriptor; +import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link Factory} that uses a default constructor and a list of setters to construct a {@link @@ -37,25 +39,48 @@ public SetterBasedCreatorFactory(Factory> setterFactory) @Override public SchemaUserTypeCreator create(TypeDescriptor typeDescriptor, Schema schema) { - List setters = setterFactory.create(typeDescriptor, schema); - return new SchemaUserTypeCreator() { - @Override - public Object create(Object... params) { - Object object; - try { - object = typeDescriptor.getRawType().getDeclaredConstructor().newInstance(); - } catch (NoSuchMethodException - | IllegalAccessException - | InvocationTargetException - | InstantiationException e) { - throw new RuntimeException("Failed to instantiate object ", e); - } - for (int i = 0; i < params.length; ++i) { - FieldValueSetter setter = setters.get(i); - setter.set(object, params[i]); + List setterList = setterFactory.create(typeDescriptor, schema); + FieldValueSetter[] setters = setterList.toArray(new FieldValueSetter[0]); + return new SetterBasedCreator(typeDescriptor, setters); + } + + /** Serializable creator caching the reflected no-arg constructor in a transient field. */ + private static final class SetterBasedCreator implements SchemaUserTypeCreator { + private final TypeDescriptor typeDescriptor; + private final FieldValueSetter[] setters; + private transient volatile @Nullable Constructor cachedCtor; + + SetterBasedCreator(TypeDescriptor typeDescriptor, FieldValueSetter[] setters) { + this.typeDescriptor = typeDescriptor; + this.setters = setters; + try { + this.cachedCtor = typeDescriptor.getRawType().getDeclaredConstructor(); + } catch (NoSuchMethodException e) { + // Preserve deferred failure inside create() for compatibility with lazy callers/tests. + this.cachedCtor = null; + } + } + + @Override + public Object create(Object... params) { + Object object; + try { + Constructor ctor = cachedCtor; + if (ctor == null) { + ctor = typeDescriptor.getRawType().getDeclaredConstructor(); + cachedCtor = ctor; } - return object; + object = ctor.newInstance(); + } catch (NoSuchMethodException + | IllegalAccessException + | InvocationTargetException + | InstantiationException e) { + throw new RuntimeException("Failed to instantiate object ", e); + } + for (int i = 0; i < params.length; ++i) { + setters[i].set(object, params[i]); } - }; + return object; + } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/AutoValueUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/AutoValueUtils.java index a9353bcaaacb..8b5b62754434 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/AutoValueUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/AutoValueUtils.java @@ -62,10 +62,12 @@ import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.InjectPackageStrategy; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.TypeConversion; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.TypeConversionsFactory; +import org.apache.beam.sdk.schemas.utils.ReflectUtils.TypeDescriptorWithSchema; import org.apache.beam.sdk.util.Preconditions; import org.apache.beam.sdk.util.common.ReflectHelpers; import org.apache.beam.sdk.values.TypeDescriptor; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; import org.checkerframework.checker.nullness.qual.Nullable; /** Utilities for managing AutoValue schemas. */ @@ -225,6 +227,49 @@ private static boolean matchConstructor( return true; } + // Anchor AutoValue builder creator caches to the user class via ClassValue so user ClassLoaders + // can be garbage collected cleanly, and key by supplier class + TypeDescriptor + Schema. + private static final class BuilderCreatorKey { + final TypeDescriptorWithSchema typeWithSchema; + final Class supplierClass; + final int hash; + + BuilderCreatorKey(TypeDescriptorWithSchema typeWithSchema, Class supplierClass) { + this.typeWithSchema = typeWithSchema; + this.supplierClass = supplierClass; + this.hash = 31 * typeWithSchema.hashCode() + supplierClass.hashCode(); + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } + if (!(o instanceof BuilderCreatorKey)) { + return false; + } + BuilderCreatorKey that = (BuilderCreatorKey) o; + return hash == that.hash + && supplierClass == that.supplierClass + && typeWithSchema.equals(that.typeWithSchema); + } + } + + private static final ClassValue>> + CACHED_BUILDER_CREATORS = + new ClassValue>>() { + @Override + protected Map> computeValue( + Class type) { + return Maps.newConcurrentMap(); + } + }; + /** * Try to find an accessible builder class for creating an AutoValue class. Otherwise return null. */ @@ -232,6 +277,25 @@ private static boolean matchConstructor( TypeDescriptor typeDescriptor, Schema schema, FieldValueTypeSupplier fieldValueTypeSupplier) { + Map> perClassCache = + CACHED_BUILDER_CREATORS.get(typeDescriptor.getRawType()); + BuilderCreatorKey key = + new BuilderCreatorKey( + TypeDescriptorWithSchema.create(typeDescriptor, schema), + fieldValueTypeSupplier.getClass()); + return perClassCache + .computeIfAbsent( + key, + k -> + Optional.ofNullable( + buildBuilderCreator(typeDescriptor, schema, fieldValueTypeSupplier))) + .orElse(null); + } + + private static @Nullable SchemaUserTypeCreator buildBuilderCreator( + TypeDescriptor typeDescriptor, + Schema schema, + FieldValueTypeSupplier fieldValueTypeSupplier) { TypeDescriptor builderTypeDescriptor = getAutoValueGeneratedBuilder(typeDescriptor); if (builderTypeDescriptor == null) { return null; diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ByteBuddyUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ByteBuddyUtils.java index db8cf786a414..90b5105dac7e 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ByteBuddyUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ByteBuddyUtils.java @@ -49,6 +49,9 @@ import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.method.MethodDescription.ForLoadedConstructor; import net.bytebuddy.description.method.MethodDescription.ForLoadedMethod; +import net.bytebuddy.description.modifier.FieldManifestation; +import net.bytebuddy.description.modifier.Ownership; +import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.description.type.PackageDescription; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeDescription.ForLoadedType; @@ -66,6 +69,7 @@ import net.bytebuddy.implementation.bytecode.assign.TypeCasting; import net.bytebuddy.implementation.bytecode.collection.ArrayAccess; import net.bytebuddy.implementation.bytecode.collection.ArrayFactory; +import net.bytebuddy.implementation.bytecode.constant.ClassConstant; import net.bytebuddy.implementation.bytecode.constant.IntegerConstant; import net.bytebuddy.implementation.bytecode.constant.NullConstant; import net.bytebuddy.implementation.bytecode.member.FieldAccess; @@ -84,8 +88,12 @@ import org.apache.beam.sdk.schemas.FieldValueSetter; import org.apache.beam.sdk.schemas.FieldValueTypeInformation; import org.apache.beam.sdk.schemas.Schema.LogicalType; +import org.apache.beam.sdk.schemas.logicaltypes.Date; +import org.apache.beam.sdk.schemas.logicaltypes.DateTime; import org.apache.beam.sdk.schemas.logicaltypes.NanosInstant; import org.apache.beam.sdk.schemas.logicaltypes.SqlTypes; +import org.apache.beam.sdk.schemas.logicaltypes.Time; +import org.apache.beam.sdk.schemas.logicaltypes.UuidLogicalType; import org.apache.beam.sdk.util.Preconditions; import org.apache.beam.sdk.util.common.ReflectHelpers; import org.apache.beam.sdk.values.TypeDescriptor; @@ -143,11 +151,19 @@ public class ByteBuddyUtils { public static final LogicalType JAVA_UUID_LOGICAL_TYPE = SqlTypes.UUID; + /** + * Marker interface implemented by generated {@link FieldValueGetter}s whose {@link + * FieldValueGetter#getRaw} directly returns an immutable JSR-310 or {@link UUID} value without + * round-tripping through {@link LogicalType#toBaseType}. + */ + @Internal + public interface DirectLogicalTypeGetter {} + /** * Returns the {@link Schema.LogicalType} that {@link StaticSchemaInference} infers for the given * Java raw type, or {@code null} if no JSR-310 / UUID inference applies. */ - static @Nullable LogicalType inferredLogicalTypeFor(Class rawType) { + public static @Nullable LogicalType inferredLogicalTypeFor(Class rawType) { if (LocalDate.class.equals(rawType)) { return JAVA_LOCAL_DATE_LOGICAL_TYPE; } else if (LocalTime.class.equals(rawType)) { @@ -162,6 +178,44 @@ public class ByteBuddyUtils { return null; } + /** + * Returns {@code true} when {@code logicalType} is the exact built-in logical type inferred for + * {@code javaRawType}, enabling zero-copy pass-through without {@code toBaseType}/{@code + * toInputType} round-trips. + */ + public static boolean matchesInferredLogicalType( + @Nullable LogicalType logicalType, Class javaRawType) { + if (logicalType == null) { + return false; + } + Class lc = logicalType.getClass(); + if (LocalDate.class.equals(javaRawType)) { + return lc == Date.class; + } else if (LocalTime.class.equals(javaRawType)) { + return lc == Time.class; + } else if (LocalDateTime.class.equals(javaRawType)) { + return lc == DateTime.class; + } else if (java.time.Instant.class.equals(javaRawType)) { + return lc == NanosInstant.class; + } else if (UUID.class.equals(javaRawType)) { + return lc == UuidLogicalType.class; + } + return false; + } + + /** + * Accepts either an already-converted Java logical-type input value (passing it through with zero + * allocation) or its base representation (converting via {@link LogicalType#toInputType}). + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public static Object convertLogicalTypeForSetter( + LogicalType logicalType, Class targetClass, Object value) { + if (targetClass.isInstance(value)) { + return value; + } + return logicalType.toInputType(value); + } + /** Maps a Java raw type to the static field name in {@link ByteBuddyUtils} that holds it. */ private static String logicalTypeFieldName(Class rawType) { if (LocalDate.class.equals(rawType)) { @@ -321,7 +375,93 @@ public interface TypeConversionsFactory { TypeConversion createSetterConversions(StackManipulation readValue); } + /** Unique probe sentinel used to detect whether a {@link TypeConversion} is an identity. */ + static final StackManipulation IDENTITY_PROBE = + new StackManipulation() { + @Override + public boolean isValid() { + return true; + } + + @Override + public Size apply(MethodVisitor methodVisitor, Context context) { + throw new UnsupportedOperationException("IDENTITY_PROBE must never be emitted"); + } + }; + + /** + * Cached Guava identity function used for map key/value pairs where one side needs no conversion. + */ + public static final Function IDENTITY_FUNCTION = input -> input; + + private static final ClassValue ENUM_CONSTANTS_CACHE = + new ClassValue() { + @Override + protected Object @Nullable [] computeValue(Class type) { + return type.getEnumConstants(); + } + }; + + /** Returns the enum constant at {@code ordinal} without cloning {@code $VALUES}. */ + public static Object enumConstantForOrdinal(Class enumClass, int ordinal) { + Object[] constants = Preconditions.checkStateNotNull(ENUM_CONSTANTS_CACHE.get(enumClass)); + if (ordinal < 0 || ordinal >= constants.length) { + throw new IllegalArgumentException( + "Unknown enum ordinal " + ordinal + " for " + enumClass.getName()); + } + return constants[ordinal]; + } + + /** Returns {@code iterable} as a {@link List} without copying if it already is one. */ + public static List ensureList(Iterable iterable) { + if (iterable instanceof List) { + return (List) iterable; + } + return Lists.newArrayList(iterable); + } + + /** Returns {@code iterable} as an {@link ArrayList} without copying if it already is one. */ + public static ArrayList ensureArrayList(Iterable iterable) { + if (iterable instanceof ArrayList) { + return (ArrayList) iterable; + } + return Lists.newArrayList(iterable); + } + + /** Eagerly transforms {@code iterable} into a pre-sized {@link ArrayList} in a single pass. */ + public static ArrayList transformToArrayList( + Iterable iterable, Function function) { + if (iterable instanceof Collection) { + Collection col = (Collection) iterable; + ArrayList result = new ArrayList<>(col.size()); + if (col instanceof List && col instanceof java.util.RandomAccess) { + List list = (List) col; + for (int i = 0, n = list.size(); i < n; i++) { + result.add(function.apply(list.get(i))); + } + } else { + for (FromT item : col) { + result.add(function.apply(item)); + } + } + return result; + } + ArrayList result = new ArrayList<>(); + for (FromT item : iterable) { + result.add(function.apply(item)); + } + return result; + } + + static boolean isIdentityConversion( + java.util.function.Function convert) { + return convert.apply(IDENTITY_PROBE) == IDENTITY_PROBE; + } + public static class DefaultTypeConversionsFactory implements TypeConversionsFactory { + public static final DefaultTypeConversionsFactory INSTANCE = + new DefaultTypeConversionsFactory(); + @Override public TypeConversion createTypeConversion(boolean returnRawTypes) { return new ConvertType(returnRawTypes); @@ -543,10 +683,12 @@ private TypeDescriptor> createIterableType( private static final ByteBuddy BYTE_BUDDY = new ByteBuddy(); + private static final String FUNCTION_INSTANCE_FIELD = "INSTANCE"; + // When processing a container (e.g. List) we need to recursively process the element type. - // This function - // generates a subclass of Function that can be used to recursively transform each element of the - // container. + // This function generates a subclass of Function that can be used to recursively transform each + // element of the container, exposing a public static INSTANCE field to avoid per-element + // allocations. static Class createCollectionTransformFunction( Type fromType, Type toType, Function convertElement) { // Generate a TypeDescription for the class we want to generate. @@ -560,6 +702,35 @@ static Class createCollectionTransformFunction( BYTE_BUDDY .with(new InjectPackageStrategy((Class) fromType)) .subclass(functionGenericType) + .defineField( + FUNCTION_INSTANCE_FIELD, + Function.class, + Visibility.PUBLIC, + Ownership.STATIC, + FieldManifestation.FINAL) + .initializer( + (methodVisitor, implementationContext, instrumentedMethod) -> { + TypeDescription instrumentedType = + implementationContext.getInstrumentedType(); + StackManipulation init = + new StackManipulation.Compound( + TypeCreation.of(instrumentedType), + Duplication.SINGLE, + MethodInvocation.invoke( + instrumentedType + .getDeclaredMethods() + .filter(ElementMatchers.isDefaultConstructor()) + .getOnly()), + FieldAccess.forField( + instrumentedType + .getDeclaredFields() + .filter(ElementMatchers.named(FUNCTION_INSTANCE_FIELD)) + .getOnly()) + .write()); + StackManipulation.Size size = + init.apply(methodVisitor, implementationContext); + return new ByteCodeAppender.Size(size.getMaximalSize(), 0); + }) .method(ElementMatchers.named("apply")) .intercept( new Implementation() { @@ -598,9 +769,26 @@ public InstrumentedType prepare(InstrumentedType instrumentedType) { .getLoaded(); } + private static StackManipulation loadFunctionInstance(ForLoadedType functionType) { + return FieldAccess.forField( + functionType + .getDeclaredFields() + .filter(ElementMatchers.named(FUNCTION_INSTANCE_FIELD)) + .getOnly()) + .read(); + } + + private static StackManipulation loadIdentityFunction() { + return FieldAccess.forField( + BYTE_BUDDY_UTILS_TYPE + .getDeclaredFields() + .filter(ElementMatchers.named("IDENTITY_FUNCTION")) + .getOnly()) + .read(); + } + // A function to transform a container, special casing List and Collection types. This is used in - // byte-buddy - // generated code. + // byte-buddy generated code. public static Iterable transformContainer( Iterable iterable, Function function) { if (iterable instanceof List) { @@ -614,22 +802,14 @@ public static Iterable transformContainer( static StackManipulation createTransformingContainer( ForLoadedType functionType, StackManipulation readValue) { - StackManipulation stackManipulation = - new Compound( - readValue, - TypeCreation.of(functionType), - Duplication.SINGLE, - MethodInvocation.invoke( - functionType - .getDeclaredMethods() - .filter(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) - .getOnly()), - MethodInvocation.invoke( - BYTE_BUDDY_UTILS_TYPE - .getDeclaredMethods() - .filter(ElementMatchers.named("transformContainer")) - .getOnly())); - return stackManipulation; + return new Compound( + readValue, + loadFunctionInstance(functionType), + MethodInvocation.invoke( + BYTE_BUDDY_UTILS_TYPE + .getDeclaredMethods() + .filter(ElementMatchers.named("transformContainer")) + .getOnly())); } public static TransformingMap getTransformingMap( @@ -648,7 +828,7 @@ public TransformingMap( Maps.newTreeMap(); // We don't support copying the comparator. Makes no sense if key // is changing. } else { - delegateMap = Maps.newHashMap(); + delegateMap = Maps.newHashMapWithExpectedSize(sourceMap.size()); } for (Map.Entry entry : sourceMap.entrySet()) { delegateMap.put(keyFunction.apply(entry.getKey()), valueFunction.apply(entry.getValue())); @@ -721,16 +901,18 @@ public boolean equals(@Nullable Object o) { if (this == o) { return true; } - if (!(o instanceof TransformingMap)) { - return false; + if (o instanceof TransformingMap) { + return Objects.equals(delegateMap, ((TransformingMap) o).delegateMap); + } + if (o instanceof Map) { + return delegateMap.equals(o); } - TransformingMap that = (TransformingMap) o; - return Objects.equals(delegateMap, that.delegateMap); + return false; } @Override public int hashCode() { - return Objects.hash(delegateMap); + return delegateMap.hashCode(); } @Override @@ -755,11 +937,14 @@ protected ConvertValueForGetter(StackManipulation readValue) { } protected TypeConversionsFactory getFactory() { - return new DefaultTypeConversionsFactory(); + return DefaultTypeConversionsFactory.INSTANCE; } @Override protected StackManipulation convertArray(TypeDescriptor type) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } // Generate the following code: // return isComponentTypePrimitive ? Arrays.asList(ArrayUtils.toObject(value)) // : Arrays.asList(value); @@ -795,10 +980,13 @@ protected StackManipulation convertArray(TypeDescriptor type) { .filter(ElementMatchers.isStatic().and(ElementMatchers.named("asList"))) .getOnly())); - // Generate a SerializableFunction to convert the element-type objects. + // Generate a Function to convert the element-type objects only when conversion is + // non-identity. StackManipulation stackManipulation; final TypeDescriptor finalComponentType = ReflectUtils.boxIfPrimitive(componentType); - if (!finalComponentType.hasUnresolvedParameters()) { + if (!finalComponentType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createGetterConversions(s).convert(finalComponentType))) { Type convertedComponentType = getFactory().createTypeConversion(true).convert(componentType); ForLoadedType functionType = @@ -818,10 +1006,15 @@ protected StackManipulation convertArray(TypeDescriptor type) { protected StackManipulation convertIterable(TypeDescriptor type) { TypeDescriptor componentType = Preconditions.checkArgumentNotNull(ReflectUtils.getIterableComponentType(type)); - Type convertedComponentType = getFactory().createTypeConversion(true).convert(componentType); - final TypeDescriptor finalComponentType = ReflectUtils.boxIfPrimitive(componentType); - if (!finalComponentType.hasUnresolvedParameters()) { + if (!finalComponentType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createGetterConversions(s).convert(finalComponentType))) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } + Type convertedComponentType = + getFactory().createTypeConversion(true).convert(componentType); ForLoadedType functionType = new ForLoadedType( createCollectionTransformFunction( @@ -839,9 +1032,15 @@ protected StackManipulation convertIterable(TypeDescriptor type) { protected StackManipulation convertCollection(TypeDescriptor type) { TypeDescriptor componentType = Preconditions.checkArgumentNotNull(ReflectUtils.getIterableComponentType(type)); - Type convertedComponentType = getFactory().createTypeConversion(true).convert(componentType); final TypeDescriptor finalComponentType = ReflectUtils.boxIfPrimitive(componentType); - if (!finalComponentType.hasUnresolvedParameters()) { + if (!finalComponentType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createGetterConversions(s).convert(finalComponentType))) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } + Type convertedComponentType = + getFactory().createTypeConversion(true).convert(componentType); ForLoadedType functionType = new ForLoadedType( createCollectionTransformFunction( @@ -859,9 +1058,15 @@ protected StackManipulation convertCollection(TypeDescriptor type) { protected StackManipulation convertList(TypeDescriptor type) { TypeDescriptor componentType = Preconditions.checkArgumentNotNull(ReflectUtils.getIterableComponentType(type)); - Type convertedComponentType = getFactory().createTypeConversion(true).convert(componentType); final TypeDescriptor finalComponentType = ReflectUtils.boxIfPrimitive(componentType); - if (!finalComponentType.hasUnresolvedParameters()) { + if (!finalComponentType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createGetterConversions(s).convert(finalComponentType))) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } + Type convertedComponentType = + getFactory().createTypeConversion(true).convert(componentType); ForLoadedType functionType = new ForLoadedType( createCollectionTransformFunction( @@ -880,41 +1085,48 @@ protected StackManipulation convertMap(TypeDescriptor type) { final TypeDescriptor keyType = ReflectUtils.getMapType(type, 0); final TypeDescriptor valueType = ReflectUtils.getMapType(type, 1); - Type convertedKeyType = getFactory().createTypeConversion(true).convert(keyType); - Type convertedValueType = getFactory().createTypeConversion(true).convert(valueType); - if (!keyType.hasUnresolvedParameters() && !valueType.hasUnresolvedParameters()) { - ForLoadedType keyFunctionType = - new ForLoadedType( - createCollectionTransformFunction( - keyType.getRawType(), - convertedKeyType, - (s) -> getFactory().createGetterConversions(s).convert(keyType))); - ForLoadedType valueFunctionType = - new ForLoadedType( - createCollectionTransformFunction( - valueType.getRawType(), - convertedValueType, - (s) -> getFactory().createGetterConversions(s).convert(valueType))); + boolean keyIdentity = + isIdentityConversion(s -> getFactory().createGetterConversions(s).convert(keyType)); + boolean valueIdentity = + isIdentityConversion(s -> getFactory().createGetterConversions(s).convert(valueType)); + if (keyIdentity && valueIdentity) { + return readValue; + } + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } + StackManipulation loadKeyFn; + if (keyIdentity) { + loadKeyFn = loadIdentityFunction(); + } else { + Type convertedKeyType = getFactory().createTypeConversion(true).convert(keyType); + ForLoadedType keyFunctionType = + new ForLoadedType( + createCollectionTransformFunction( + keyType.getRawType(), + convertedKeyType, + (s) -> getFactory().createGetterConversions(s).convert(keyType))); + loadKeyFn = loadFunctionInstance(keyFunctionType); + } + StackManipulation loadValueFn; + if (valueIdentity) { + loadValueFn = loadIdentityFunction(); + } else { + Type convertedValueType = getFactory().createTypeConversion(true).convert(valueType); + ForLoadedType valueFunctionType = + new ForLoadedType( + createCollectionTransformFunction( + valueType.getRawType(), + convertedValueType, + (s) -> getFactory().createGetterConversions(s).convert(valueType))); + loadValueFn = loadFunctionInstance(valueFunctionType); + } StackManipulation stackManipulation = new Compound( readValue, - TypeCreation.of(keyFunctionType), - Duplication.SINGLE, - MethodInvocation.invoke( - keyFunctionType - .getDeclaredMethods() - .filter( - ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) - .getOnly()), - TypeCreation.of(valueFunctionType), - Duplication.SINGLE, - MethodInvocation.invoke( - valueFunctionType - .getDeclaredMethods() - .filter( - ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) - .getOnly()), + loadKeyFn, + loadValueFn, MethodInvocation.invoke( BYTE_BUDDY_UTILS_TYPE .getDeclaredMethods() @@ -1112,11 +1324,14 @@ protected ConvertValueForSetter(StackManipulation readValue) { } protected TypeConversionsFactory getFactory() { - return new DefaultTypeConversionsFactory(); + return DefaultTypeConversionsFactory.INSTANCE; } @Override protected StackManipulation convertArray(TypeDescriptor type) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } // Generate the following code: // T[] toArray = (T[]) value.toArray(new T[0]); // return isPrimitive ? toArray : ArrayUtils.toPrimitive(toArray); @@ -1135,7 +1350,9 @@ protected StackManipulation convertArray(TypeDescriptor type) { Type rowElementType = getFactory().createTypeConversion(false).convert(componentType); final TypeDescriptor arrayElementType = ReflectUtils.boxIfPrimitive(componentType); StackManipulation readTransformedValue = readValue; - if (!arrayElementType.hasUnresolvedParameters()) { + if (!arrayElementType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createSetterConversions(s).convert(arrayElementType))) { ForLoadedType conversionFunction = new ForLoadedType( createCollectionTransformFunction( @@ -1191,8 +1408,13 @@ protected StackManipulation convertArray(TypeDescriptor type) { protected StackManipulation convertIterable(TypeDescriptor type) { final TypeDescriptor iterableElementType = Preconditions.checkArgumentNotNull(ReflectUtils.getIterableComponentType(type)); - Type rowElementType = getFactory().createTypeConversion(false).convert(iterableElementType); - if (!iterableElementType.hasUnresolvedParameters()) { + if (!iterableElementType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createSetterConversions(s).convert(iterableElementType))) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } + Type rowElementType = getFactory().createTypeConversion(false).convert(iterableElementType); ForLoadedType conversionFunction = new ForLoadedType( createCollectionTransformFunction( @@ -1211,9 +1433,14 @@ protected StackManipulation convertIterable(TypeDescriptor type) { protected StackManipulation convertCollection(TypeDescriptor type) { final TypeDescriptor collectionElementType = Preconditions.checkArgumentNotNull(ReflectUtils.getIterableComponentType(type)); - Type rowElementType = getFactory().createTypeConversion(false).convert(collectionElementType); - - if (!collectionElementType.hasUnresolvedParameters()) { + if (!collectionElementType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createSetterConversions(s).convert(collectionElementType))) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } + Type rowElementType = + getFactory().createTypeConversion(false).convert(collectionElementType); ForLoadedType conversionFunction = new ForLoadedType( createCollectionTransformFunction( @@ -1230,32 +1457,45 @@ protected StackManipulation convertCollection(TypeDescriptor type) { @Override protected StackManipulation convertList(TypeDescriptor type) { + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } final TypeDescriptor collectionElementType = Preconditions.checkArgumentNotNull(ReflectUtils.getIterableComponentType(type)); - Type rowElementType = getFactory().createTypeConversion(false).convert(collectionElementType); - - StackManipulation readTrasformedValue = readValue; - if (!collectionElementType.hasUnresolvedParameters()) { + if (!collectionElementType.hasUnresolvedParameters() + && !isIdentityConversion( + s -> getFactory().createSetterConversions(s).convert(collectionElementType))) { + Type rowElementType = + getFactory().createTypeConversion(false).convert(collectionElementType); ForLoadedType conversionFunction = new ForLoadedType( createCollectionTransformFunction( TypeDescriptor.of(rowElementType).getRawType(), collectionElementType.getRawType(), (s) -> getFactory().createSetterConversions(s).convert(collectionElementType))); - readTrasformedValue = createTransformingContainer(conversionFunction, readValue); + StackManipulation transformedList = + new Compound( + readValue, + loadFunctionInstance(conversionFunction), + MethodInvocation.invoke( + BYTE_BUDDY_UTILS_TYPE + .getDeclaredMethods() + .filter(ElementMatchers.named("transformToArrayList")) + .getOnly())); + return new ShortCircuitReturnNull(readValue, transformedList); } - // TODO: Don't copy if already a list! - StackManipulation transformedList = + // If the element conversion is identity, only wrap/copy when the runtime value is not + // already of the required List/ArrayList type. + String helperName = type.getRawType().equals(List.class) ? "ensureList" : "ensureArrayList"; + StackManipulation ensured = new Compound( - readTrasformedValue, + readValue, MethodInvocation.invoke( - new ForLoadedType(Lists.class) + BYTE_BUDDY_UTILS_TYPE .getDeclaredMethods() - .filter( - ElementMatchers.named("newArrayList") - .and(ElementMatchers.takesArguments(Iterable.class))) + .filter(ElementMatchers.named(helperName)) .getOnly())); - return new ShortCircuitReturnNull(readValue, transformedList); + return new ShortCircuitReturnNull(readValue, ensured); } @Override @@ -1264,54 +1504,81 @@ protected StackManipulation convertMap(TypeDescriptor type) { Preconditions.checkArgumentNotNull(ReflectUtils.getMapType(type, 0)); final TypeDescriptor valueElementType = Preconditions.checkArgumentNotNull(ReflectUtils.getMapType(type, 1)); - Type rowKeyType = getFactory().createTypeConversion(false).convert(keyElementType); - Type rowValueType = getFactory().createTypeConversion(false).convert(valueElementType); - StackManipulation readTrasformedValue = readValue; if (!keyElementType.hasUnresolvedParameters() && !valueElementType.hasUnresolvedParameters()) { - ForLoadedType keyConversionFunction = - new ForLoadedType( - createCollectionTransformFunction( - TypeDescriptor.of(rowKeyType).getRawType(), - keyElementType.getRawType(), - (s) -> getFactory().createSetterConversions(s).convert(keyElementType))); - ForLoadedType valueConversionFunction = - new ForLoadedType( - createCollectionTransformFunction( - TypeDescriptor.of(rowValueType).getRawType(), - valueElementType.getRawType(), - (s) -> getFactory().createSetterConversions(s).convert(valueElementType))); - readTrasformedValue = + boolean keyIdentity = + isIdentityConversion( + s -> getFactory().createSetterConversions(s).convert(keyElementType)); + boolean valueIdentity = + isIdentityConversion( + s -> getFactory().createSetterConversions(s).convert(valueElementType)); + if (keyIdentity && valueIdentity) { + return readValue; + } + if (readValue == IDENTITY_PROBE) { + return StackManipulation.Illegal.INSTANCE; + } + StackManipulation loadKeyFn; + if (keyIdentity) { + loadKeyFn = loadIdentityFunction(); + } else { + Type rowKeyType = getFactory().createTypeConversion(false).convert(keyElementType); + ForLoadedType keyConversionFunction = + new ForLoadedType( + createCollectionTransformFunction( + TypeDescriptor.of(rowKeyType).getRawType(), + keyElementType.getRawType(), + (s) -> getFactory().createSetterConversions(s).convert(keyElementType))); + loadKeyFn = loadFunctionInstance(keyConversionFunction); + } + StackManipulation loadValueFn; + if (valueIdentity) { + loadValueFn = loadIdentityFunction(); + } else { + Type rowValueType = getFactory().createTypeConversion(false).convert(valueElementType); + ForLoadedType valueConversionFunction = + new ForLoadedType( + createCollectionTransformFunction( + TypeDescriptor.of(rowValueType).getRawType(), + valueElementType.getRawType(), + (s) -> getFactory().createSetterConversions(s).convert(valueElementType))); + loadValueFn = loadFunctionInstance(valueConversionFunction); + } + StackManipulation transformedMap = new Compound( readValue, - TypeCreation.of(keyConversionFunction), - Duplication.SINGLE, - MethodInvocation.invoke( - keyConversionFunction - .getDeclaredMethods() - .filter( - ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) - .getOnly()), - TypeCreation.of(valueConversionFunction), - Duplication.SINGLE, - MethodInvocation.invoke( - valueConversionFunction - .getDeclaredMethods() - .filter( - ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) - .getOnly()), + loadKeyFn, + loadValueFn, MethodInvocation.invoke( BYTE_BUDDY_UTILS_TYPE .getDeclaredMethods() .filter(ElementMatchers.named("getTransformingMap")) .getOnly())); + return new ShortCircuitReturnNull(readValue, transformedMap); } - return new ShortCircuitReturnNull(readValue, readTrasformedValue); + return readValue; } @Override protected StackManipulation convertDateTime(TypeDescriptor type) { + // Fast path: when target is org.joda.time.Instant or ReadableInstant, call toInstant() + // which returns `this` with zero allocation when value is already an Instant. + Class rawType = type.getRawType(); + if (rawType.equals(Instant.class) || rawType.equals(ReadableInstant.class)) { + StackManipulation toInstant = + new Compound( + readValue, + TypeCasting.to(READABLE_INSTANT_TYPE), + MethodInvocation.invoke( + READABLE_INSTANT_TYPE + .getDeclaredMethods() + .filter( + ElementMatchers.named("toInstant") + .and(ElementMatchers.takesArguments(0))) + .getOnly())); + return new ShortCircuitReturnNull(readValue, toInstant); + } // The setter might be called with a different subclass of ReadableInstant than the one stored // in this POJO. We must extract the value passed into the setter and copy it into an instance // that the POJO can accept. @@ -1443,49 +1710,38 @@ protected StackManipulation convertPrimitive(TypeDescriptor type) { protected StackManipulation convertEnum(TypeDescriptor type) { ForLoadedType loadedType = new ForLoadedType(type.getRawType()); - // Convert the stored ordinal back to the Java enum constant. + // Look up enum constant via cached ClassValue to avoid cloning $VALUES per call. StackManipulation stackManipulation = new Compound( - // Call EnumType::values() to get an array of all enum constants. - MethodInvocation.invoke( - loadedType - .getDeclaredMethods() - .filter( - ElementMatchers.named("values") - .and( - ElementMatchers.isStatic() - .and(ElementMatchers.takesArguments(0)))) - .getOnly()), - // Read the integer enum value. + ClassConstant.of(loadedType), readValue, - // Unbox Integer -> int before accessing the array. Assigner.DEFAULT.assign( INTEGER_TYPE.asBoxed().asGenericType(), INTEGER_TYPE.asUnboxed().asGenericType(), Typing.STATIC), - // Access the array to return the Java enum type. - ArrayAccess.REFERENCE.load()); + MethodInvocation.invoke( + BYTE_BUDDY_UTILS_TYPE + .getDeclaredMethods() + .filter(ElementMatchers.named("enumConstantForOrdinal")) + .getOnly()), + TypeCasting.to(loadedType)); return new ShortCircuitReturnNull(readValue, stackManipulation); } @Override protected StackManipulation convertLogicalType(TypeDescriptor type) { - // Equivalent code: return (JavaType) STATIC_LOGICAL_TYPE.toInputType(value); - // FromRowUsingCreator already converted the row's input-type value (e.g. LocalDate) - // to the LogicalType's base value (e.g. Long) before invoking the generated creator, - // so we receive the base type here and need to project back to the POJO field's - // Java type. + // Accepts either the Java input type directly (when FromRowUsingCreator skips toBaseType) + // or the LogicalType's base representation (for direct caller compatibility). ForLoadedType loadedType = new ForLoadedType(type.getRawType()); StackManipulation stackManipulation = new Compound( loadLogicalType(type.getRawType()), + ClassConstant.of(loadedType), readValue, MethodInvocation.invoke( - LOGICAL_TYPE_TYPE + BYTE_BUDDY_UTILS_TYPE .getDeclaredMethods() - .filter( - ElementMatchers.named("toInputType") - .and(ElementMatchers.takesArguments(1))) + .filter(ElementMatchers.named("convertLogicalTypeForSetter")) .getOnly()), TypeCasting.to(loadedType)); return new ShortCircuitReturnNull(readValue, stackManipulation); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ConvertHelpers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ConvertHelpers.java index 6b7801b6b3e6..c3408fd36d94 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ConvertHelpers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ConvertHelpers.java @@ -23,6 +23,8 @@ import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; +import java.util.Map; +import java.util.Objects; import java.util.ServiceLoader; import javax.annotation.concurrent.GuardedBy; import net.bytebuddy.ByteBuddy; @@ -46,8 +48,10 @@ import org.apache.beam.sdk.schemas.SchemaRegistry; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.TypeConversionsFactory; import org.apache.beam.sdk.transforms.SerializableFunction; +import org.apache.beam.sdk.transforms.SerializableFunctions; import org.apache.beam.sdk.util.common.ReflectHelpers; import org.apache.beam.sdk.values.TypeDescriptor; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.primitives.Primitives; import org.checkerframework.checker.nullness.qual.Nullable; import org.slf4j.Logger; @@ -68,6 +72,37 @@ private static class SchemaInformationProviders { private static final Logger LOG = LoggerFactory.getLogger(ConvertHelpers.class); private static final Object lock = new Object(); + private static final ByteBuddy BYTE_BUDDY = new ByteBuddy(); + private static final Map> + CACHED_PRIMITIVE_CONVERTERS = Maps.newConcurrentMap(); + + private static final class ConvertPrimitiveKey { + final Type expectedInputType; + final TypeDescriptor outputType; + + ConvertPrimitiveKey(Type expectedInputType, TypeDescriptor outputType) { + this.expectedInputType = expectedInputType; + this.outputType = outputType; + } + + @Override + public boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } + if (!(o instanceof ConvertPrimitiveKey)) { + return false; + } + ConvertPrimitiveKey that = (ConvertPrimitiveKey) o; + return Objects.equals(expectedInputType, that.expectedInputType) + && Objects.equals(outputType, that.outputType); + } + + @Override + public int hashCode() { + return 31 * Objects.hashCode(expectedInputType) + outputType.hashCode(); + } + } /** Return value after converting a schema. */ @SuppressFBWarnings( @@ -182,18 +217,43 @@ public static SerializableFunction getConvertPrimitive( outputType = TypeDescriptor.of(Primitives.wrap(outputType.getRawType())); } + final TypeDescriptor resolvedOutputType = outputType; + // Only cache for the stateless DefaultTypeConversionsFactory so stateful custom factories never + // collide in the shared map. + if (typeConversionsFactory.getClass() == ByteBuddyUtils.DefaultTypeConversionsFactory.class) { + ConvertPrimitiveKey key = new ConvertPrimitiveKey(expectedInputType, resolvedOutputType); + return (SerializableFunction) + CACHED_PRIMITIVE_CONVERTERS.computeIfAbsent( + key, + k -> + buildConvertPrimitive( + expectedInputType, resolvedOutputType, typeConversionsFactory)); + } + return (SerializableFunction) + buildConvertPrimitive(expectedInputType, resolvedOutputType, typeConversionsFactory); + } + + @SuppressWarnings("unchecked") + private static SerializableFunction buildConvertPrimitive( + Type expectedInputType, + TypeDescriptor resolvedOutputType, + TypeConversionsFactory typeConversionsFactory) { + if (ByteBuddyUtils.isIdentityConversion( + s -> typeConversionsFactory.createSetterConversions(s).convert(resolvedOutputType))) { + return SerializableFunctions.identity(); + } TypeDescription.Generic genericType = TypeDescription.Generic.Builder.parameterizedType( - SerializableFunction.class, expectedInputType, outputType.getType()) + SerializableFunction.class, expectedInputType, resolvedOutputType.getType()) .build(); DynamicType.Builder builder = - (DynamicType.Builder) new ByteBuddy().subclass(genericType); + (DynamicType.Builder) BYTE_BUDDY.subclass(genericType); try { return builder .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) .method(ElementMatchers.named("apply")) - .intercept(new ConvertPrimitiveInstruction(outputType, typeConversionsFactory)) + .intercept(new ConvertPrimitiveInstruction(resolvedOutputType, typeConversionsFactory)) .make() .load( ReflectHelpers.findClassLoader(), getClassLoadingStrategy(SerializableFunction.class)) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JavaBeanUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JavaBeanUtils.java index 10f465787216..fa193e93703f 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JavaBeanUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JavaBeanUtils.java @@ -22,30 +22,40 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import net.bytebuddy.ByteBuddy; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.method.MethodDescription.ForLoadedMethod; import net.bytebuddy.description.type.TypeDescription; +import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.scaffold.InstrumentedType; import net.bytebuddy.implementation.FixedValue; import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.bytecode.ByteCodeAppender; import net.bytebuddy.implementation.bytecode.ByteCodeAppender.Size; +import net.bytebuddy.implementation.bytecode.Duplication; import net.bytebuddy.implementation.bytecode.Removal; import net.bytebuddy.implementation.bytecode.StackManipulation; +import net.bytebuddy.implementation.bytecode.TypeCreation; import net.bytebuddy.implementation.bytecode.assign.TypeCasting; +import net.bytebuddy.implementation.bytecode.collection.ArrayAccess; +import net.bytebuddy.implementation.bytecode.constant.IntegerConstant; import net.bytebuddy.implementation.bytecode.member.MethodInvocation; import net.bytebuddy.implementation.bytecode.member.MethodReturn; import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess; import net.bytebuddy.jar.asm.ClassWriter; import net.bytebuddy.matcher.ElementMatchers; +import net.bytebuddy.pool.TypePool; +import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.schemas.FieldValueGetter; import org.apache.beam.sdk.schemas.FieldValueHaver; import org.apache.beam.sdk.schemas.FieldValueSetter; @@ -55,6 +65,7 @@ import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConstructorCreateInstruction; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.InjectPackageStrategy; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.StaticFactoryMethodInstruction; +import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.TypeConversion; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.TypeConversionsFactory; import org.apache.beam.sdk.schemas.utils.ReflectUtils.TypeDescriptorWithSchema; import org.apache.beam.sdk.util.Preconditions; @@ -207,11 +218,57 @@ DynamicType.Builder> implementGetterMethods( DynamicType.Builder> builder, FieldValueTypeInformation typeInformation, TypeConversionsFactory typeConversionsFactory) { - return builder - .method(ElementMatchers.named("name")) - .intercept(FixedValue.reference(typeInformation.getName())) - .method(ElementMatchers.named("get")) - .intercept(new InvokeGetterInstruction(typeInformation, typeConversionsFactory)); + builder = + builder + .method(ElementMatchers.named("name")) + .intercept(FixedValue.reference(typeInformation.getName())) + .method(ElementMatchers.named("get")) + .intercept(new InvokeGetterInstruction(typeInformation, typeConversionsFactory)); + if (typeConversionsFactory.getClass() == ByteBuddyUtils.DefaultTypeConversionsFactory.class + && ByteBuddyUtils.inferredLogicalTypeFor(typeInformation.getRawType()) != null) { + builder = + builder + .implement(ByteBuddyUtils.DirectLogicalTypeGetter.class) + .method(ElementMatchers.named("getRaw")) + .intercept(new InvokeRawGetterInstruction(typeInformation)); + } + return builder; + } + + // Invokes the JavaBean getter directly without logical-type toBaseType conversion. + private static class InvokeRawGetterInstruction implements Implementation { + private final FieldValueTypeInformation typeInformation; + + InvokeRawGetterInstruction(FieldValueTypeInformation typeInformation) { + this.typeInformation = typeInformation; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(final Target implementationTarget) { + return (methodVisitor, implementationContext, instrumentedMethod) -> { + int numLocals = 1 + instrumentedMethod.getParameters().size(); + Method method = + Preconditions.checkStateNotNull( + typeInformation.getMethod(), GETTER_WITH_NULL_METHOD_ERROR); + StackManipulation cast = + typeInformation.getRawType().isAssignableFrom(method.getReturnType()) + ? StackManipulation.Trivial.INSTANCE + : TypeCasting.to(TypeDescription.ForLoadedType.of(typeInformation.getRawType())); + StackManipulation stackManipulation = + new StackManipulation.Compound( + MethodVariableAccess.REFERENCE.loadFrom(1), + MethodInvocation.invoke(new ForLoadedMethod(method)), + cast, + MethodReturn.REFERENCE); + StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext); + return new Size(size.getMaximalSize(), numLocals); + }; + } } // The list of setters for a class is cached, so we only create the classes the first time @@ -418,6 +475,323 @@ public static SchemaUserTypeCreator createStaticCreator( } } + // Above this field count, setter-based creator generation falls back to SetterBasedCreatorFactory + // to stay well below HotSpot C2's 8KB HugeMethodLimit even when fields require type conversions. + private static final int MAX_INLINED_SETTER_CREATOR_FIELDS = 128; + private static final int MAX_SETTER_CREATORS_PER_CLASS = 32; + + private static final class SetterCreatorKey { + final TypeDescriptorWithSchema typeWithSchema; + final Class supplierClass; + final Class factoryClass; + final int hash; + + SetterCreatorKey( + TypeDescriptorWithSchema typeWithSchema, Class supplierClass, Class factoryClass) { + this.typeWithSchema = typeWithSchema; + this.supplierClass = supplierClass; + this.factoryClass = factoryClass; + int h = typeWithSchema.hashCode(); + h = 31 * h + supplierClass.hashCode(); + h = 31 * h + factoryClass.hashCode(); + this.hash = h; + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } + if (!(o instanceof SetterCreatorKey)) { + return false; + } + SetterCreatorKey that = (SetterCreatorKey) o; + return hash == that.hash + && supplierClass == that.supplierClass + && factoryClass == that.factoryClass + && typeWithSchema.equals(that.typeWithSchema); + } + } + + // Dedicated ClassValue-anchored cache for generated setter creators (separate from + // CACHED_CREATORS used by constructor/static creators) so user ClassLoaders are never pinned. + private static final ClassValue> + SETTER_CREATOR_CACHE = + new ClassValue>() { + @Override + protected ConcurrentHashMap computeValue( + Class type) { + return new ConcurrentHashMap<>(); + } + }; + + private static boolean isClassAccessibleFromPackage(Class clazz, @Nullable Package fromPkg) { + if (clazz.isAnonymousClass() || clazz.isLocalClass() || clazz.isSynthetic()) { + return false; + } + if (clazz.getCanonicalName() == null) { + return false; + } + if (clazz.getEnclosingClass() != null + && !clazz.isInterface() + && !clazz.isEnum() + && !Modifier.isStatic(clazz.getModifiers())) { + return false; + } + for (Class c = clazz; c != null; c = c.getEnclosingClass()) { + int m = c.getModifiers(); + if (Modifier.isPrivate(m) || Modifier.isProtected(m)) { + return false; + } + if (!Modifier.isPublic(m)) { + Package cPkg = c.getPackage(); + if (fromPkg == null || cPkg == null || !fromPkg.getName().equals(cPkg.getName())) { + return false; + } + } + } + return true; + } + + /** + * Returns a cached ByteBuddy-generated {@link SchemaUserTypeCreator} that constructs {@code + * typeDescriptor} via its accessible no-arg constructor and invokes each setter directly, or + * {@code null} if a direct bytecode creator cannot be generated (e.g., inaccessible + * class/constructor/setter, default package, or excessive field count). + */ + @Internal + public static @Nullable SchemaUserTypeCreator getSetterCreator( + TypeDescriptor typeDescriptor, + Schema schema, + FieldValueTypeSupplier setterTypeSupplier, + TypeConversionsFactory typeConversionsFactory) { + Class clazz = typeDescriptor.getRawType(); + if (schema.getFieldCount() > MAX_INLINED_SETTER_CREATOR_FIELDS) { + return null; + } + Package pkg = clazz.getPackage(); + if (pkg == null) { + return null; + } + String pkgName = pkg.getName(); + if (pkgName.startsWith("java.") + || pkgName.startsWith("javax.") + || pkgName.startsWith("sun.") + || pkgName.startsWith("jdk.")) { + return null; + } + if (Modifier.isAbstract(clazz.getModifiers()) + || clazz.isInterface() + || !isClassAccessibleFromPackage(clazz, pkg)) { + return null; + } + Constructor defaultCtor; + try { + defaultCtor = clazz.getDeclaredConstructor(); + } catch (NoSuchMethodException e) { + return null; + } + int ctorMods = defaultCtor.getModifiers(); + if (Modifier.isPrivate(ctorMods) || Modifier.isProtected(ctorMods)) { + return null; + } + List setterTypes = setterTypeSupplier.get(typeDescriptor, schema); + if (setterTypes.size() != schema.getFieldCount()) { + return null; + } + for (FieldValueTypeInformation info : setterTypes) { + Method m = info.getMethod(); + if (m == null) { + return null; + } + int mMods = m.getModifiers(); + if (Modifier.isPrivate(mMods) || Modifier.isProtected(mMods) || Modifier.isStatic(mMods)) { + return null; + } + Class declClass = m.getDeclaringClass(); + if (!isClassAccessibleFromPackage(declClass, pkg)) { + return null; + } + if (!Modifier.isPublic(mMods)) { + Package declPkg = declClass.getPackage(); + if (declPkg == null || !pkgName.equals(declPkg.getName())) { + return null; + } + } + Class[] paramTypes = m.getParameterTypes(); + if (paramTypes.length != 1) { + return null; + } + Class pType = paramTypes[0]; + while (pType.isArray()) { + pType = pType.getComponentType(); + } + if (!pType.isPrimitive() && !isClassAccessibleFromPackage(pType, pkg)) { + return null; + } + } + boolean canCache = + typeConversionsFactory.getClass() == ByteBuddyUtils.DefaultTypeConversionsFactory.class; + if (!canCache) { + return tryCreateSetterCreator(clazz, setterTypes, typeConversionsFactory); + } + ConcurrentHashMap perClassCache = + SETTER_CREATOR_CACHE.get(clazz); + SetterCreatorKey key = + new SetterCreatorKey( + TypeDescriptorWithSchema.create(typeDescriptor, schema), + setterTypeSupplier.getClass(), + typeConversionsFactory.getClass()); + SchemaUserTypeCreator existing = perClassCache.get(key); + if (existing != null) { + return existing; + } + if (perClassCache.size() >= MAX_SETTER_CREATORS_PER_CLASS) { + return null; + } + SchemaUserTypeCreator created = + tryCreateSetterCreator(clazz, setterTypes, typeConversionsFactory); + if (created == null) { + return null; + } + SchemaUserTypeCreator prev = perClassCache.putIfAbsent(key, created); + return prev != null ? prev : created; + } + + private static @Nullable SchemaUserTypeCreator tryCreateSetterCreator( + Class clazz, + List setterTypes, + TypeConversionsFactory typeConversionsFactory) { + try { + DynamicType.Builder builder = + BYTE_BUDDY + .with(new InjectPackageStrategy(clazz)) + .subclass(SchemaUserTypeCreator.class) + .method(ElementMatchers.named("create")) + .intercept( + new SetMethodCreateInstruction(setterTypes, clazz, typeConversionsFactory)); + ClassLoader targetLoader = ReflectHelpers.findClassLoader(clazz.getClassLoader()); + TypePool typePool = + TypePool.Default.of( + new ClassFileLocator.Compound( + ClassFileLocator.ForClassLoader.of(targetLoader), + ClassFileLocator.ForClassLoader.of(JavaBeanUtils.class.getClassLoader()))); + return builder + .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) + .make(typePool) + .load(targetLoader, getClassLoadingStrategy(clazz)) + .getLoaded() + .getDeclaredConstructor() + .newInstance(); + } catch (Exception | LinkageError e) { + // Fall back cleanly to SetterBasedCreatorFactory on sealed packages or classloader limits. + return null; + } + } + + private static class SetMethodCreateInstruction implements Implementation { + private final List setterTypes; + private final Class beanClass; + private final TypeConversionsFactory typeConversionsFactory; + + SetMethodCreateInstruction( + List setterTypes, + Class beanClass, + TypeConversionsFactory typeConversionsFactory) { + this.setterTypes = setterTypes; + this.beanClass = beanClass; + this.typeConversionsFactory = typeConversionsFactory; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(final Target implementationTarget) { + return (methodVisitor, implementationContext, instrumentedMethod) -> { + int baseLocals = 1 + instrumentedMethod.getParameters().size(); + int tempLocal = baseLocals; + boolean usedTemp = false; + + TypeDescription.ForLoadedType loadedType = new TypeDescription.ForLoadedType(beanClass); + StackManipulation stackManipulation = + new StackManipulation.Compound( + TypeCreation.of(loadedType), + Duplication.SINGLE, + MethodInvocation.invoke( + loadedType + .getDeclaredMethods() + .filter( + ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) + .getOnly())); + + TypeConversion convertType = typeConversionsFactory.createTypeConversion(true); + for (int i = 0; i < setterTypes.size(); i++) { + FieldValueTypeInformation typeInfo = setterTypes.get(i); + Method setter = + Preconditions.checkStateNotNull(typeInfo.getMethod(), SETTER_WITH_NULL_METHOD_ERROR); + TypeDescription.ForLoadedType convertedType = + new TypeDescription.ForLoadedType((Class) convertType.convert(typeInfo.getType())); + StackManipulation readParam = + new StackManipulation.Compound( + MethodVariableAccess.REFERENCE.loadFrom(1), + IntegerConstant.forValue(i), + ArrayAccess.REFERENCE.load(), + TypeCasting.to(convertedType)); + StackManipulation convertedValue; + if (typeInfo.getRawType().isPrimitive() + || ByteBuddyUtils.isIdentityConversion( + s -> + typeConversionsFactory + .createSetterConversions(s) + .convert(typeInfo.getType()))) { + convertedValue = + typeConversionsFactory + .createSetterConversions(readParam) + .convert(typeInfo.getType()); + } else { + // Spill param to reusable local once to avoid double aaload/checkcast in null check. + usedTemp = true; + StackManipulation storeParam = + new StackManipulation.Compound( + readParam, MethodVariableAccess.REFERENCE.storeAt(tempLocal)); + StackManipulation loadParam = MethodVariableAccess.REFERENCE.loadFrom(tempLocal); + convertedValue = + new StackManipulation.Compound( + storeParam, + typeConversionsFactory + .createSetterConversions(loadParam) + .convert(typeInfo.getType())); + } + StackManipulation invokeSetter = MethodInvocation.invoke(new ForLoadedMethod(setter)); + Class returnType = setter.getReturnType(); + StackManipulation discardReturn = + returnType.equals(Void.TYPE) + ? StackManipulation.Trivial.INSTANCE + : Removal.of(new TypeDescription.ForLoadedType(returnType)); + stackManipulation = + new StackManipulation.Compound( + stackManipulation, + Duplication.SINGLE, + convertedValue, + invokeSetter, + discardReturn); + } + stackManipulation = + new StackManipulation.Compound(stackManipulation, MethodReturn.REFERENCE); + StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext); + return new Size(size.getMaximalSize(), usedTemp ? baseLocals + 1 : baseLocals); + }; + } + } + public static > Comparator comparingNullFirst( Function keyExtractor) { return Comparator.comparing(keyExtractor, Comparator.nullsFirst(Comparator.naturalOrder())); @@ -453,24 +827,45 @@ public ByteCodeAppender appender(final Target implementationTarget) { ? StackManipulation.Trivial.INSTANCE : TypeCasting.to(TypeDescription.ForLoadedType.of(typeInformation.getRawType())); - // StackManipulation that will read the value from the class field. + // StackManipulation that reads the value from the getter. + Method method = + Preconditions.checkStateNotNull( + typeInformation.getMethod(), GETTER_WITH_NULL_METHOD_ERROR); StackManipulation readValue = new StackManipulation.Compound( // Method param is offset 1 (offset 0 is the this parameter). MethodVariableAccess.REFERENCE.loadFrom(1), // Invoke the getter - MethodInvocation.invoke( - new ForLoadedMethod( - Preconditions.checkStateNotNull( - typeInformation.getMethod(), GETTER_WITH_NULL_METHOD_ERROR))), + MethodInvocation.invoke(new ForLoadedMethod(method)), cast); - StackManipulation stackManipulation = - new StackManipulation.Compound( - typeConversionsFactory - .createGetterConversions(readValue) - .convert(typeInformation.getType()), - MethodReturn.REFERENCE); + StackManipulation stackManipulation; + if (!method.getReturnType().isPrimitive() + && !ByteBuddyUtils.isIdentityConversion( + s -> + typeConversionsFactory + .createGetterConversions(s) + .convert(typeInformation.getType()))) { + // Spill non-primitive getter result once so null checks don't invoke the getter twice. + int tempLocal = numLocals; + numLocals++; + StackManipulation loadTemp = MethodVariableAccess.REFERENCE.loadFrom(tempLocal); + stackManipulation = + new StackManipulation.Compound( + readValue, + MethodVariableAccess.REFERENCE.storeAt(tempLocal), + typeConversionsFactory + .createGetterConversions(loadTemp) + .convert(typeInformation.getType()), + MethodReturn.REFERENCE); + } else { + stackManipulation = + new StackManipulation.Compound( + typeConversionsFactory + .createGetterConversions(readValue) + .convert(typeInformation.getType()), + MethodReturn.REFERENCE); + } StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext); return new Size(size.getMaximalSize(), numLocals); @@ -521,8 +916,11 @@ public ByteCodeAppender appender(final Target implementationTarget) { // Now update the field and return void. MethodInvocation.invoke(new ForLoadedMethod(method))); if (!setterMethodReturnsVoid) { - // Discard return type; - stackManipulation = new StackManipulation.Compound(stackManipulation, Removal.SINGLE); + // Discard return value (handles both 1-slot and 2-slot long/double fluent setters). + stackManipulation = + new StackManipulation.Compound( + stackManipulation, + Removal.of(new TypeDescription.ForLoadedType(method.getReturnType()))); } stackManipulation = new StackManipulation.Compound(stackManipulation, MethodReturn.VOID); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/POJOUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/POJOUtils.java index 3aac12a9169b..41b1601c929a 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/POJOUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/POJOUtils.java @@ -24,12 +24,15 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import net.bytebuddy.ByteBuddy; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.field.FieldDescription.ForLoadedField; +import net.bytebuddy.description.modifier.Ownership; +import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeDescription.ForLoadedType; import net.bytebuddy.dynamic.DynamicType; @@ -49,6 +52,7 @@ import net.bytebuddy.implementation.bytecode.member.MethodReturn; import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess; import net.bytebuddy.jar.asm.ClassWriter; +import net.bytebuddy.jar.asm.Opcodes; import net.bytebuddy.matcher.ElementMatchers; import org.apache.beam.sdk.schemas.FieldValueGetter; import org.apache.beam.sdk.schemas.FieldValueSetter; @@ -147,6 +151,11 @@ public static SchemaUserTypeCreator getSetFieldCreator( }); } + // Maximum fields inlined into a single create(Object[]) method before splitting into chunked + // static helpers so wide POJOs stay well below HotSpot C2's 8KB HugeMethodLimit. + private static final int MAX_INLINED_CREATOR_FIELDS = 128; + private static final int CREATOR_CHUNK_SIZE = 64; + private static SchemaUserTypeCreator createSetFieldCreator( Class clazz, Schema schema, @@ -154,11 +163,29 @@ private static SchemaUserTypeCreator createSetFieldCreator( TypeConversionsFactory typeConversionsFactory) { try { DynamicType.Builder builder = - BYTE_BUDDY - .with(new InjectPackageStrategy(clazz)) - .subclass(SchemaUserTypeCreator.class) - .method(ElementMatchers.named("create")) - .intercept(new SetFieldCreateInstruction(types, clazz, typeConversionsFactory)); + BYTE_BUDDY.with(new InjectPackageStrategy(clazz)).subclass(SchemaUserTypeCreator.class); + if (types.size() <= MAX_INLINED_CREATOR_FIELDS) { + builder = + builder + .method(ElementMatchers.named("create")) + .intercept(new SetFieldCreateInstruction(types, clazz, typeConversionsFactory)); + } else { + int chunkCount = (types.size() + CREATOR_CHUNK_SIZE - 1) / CREATOR_CHUNK_SIZE; + for (int c = 0; c < chunkCount; c++) { + int start = c * CREATOR_CHUNK_SIZE; + int end = Math.min(start + CREATOR_CHUNK_SIZE, types.size()); + builder = + builder + .defineMethod("setChunk" + c, void.class, Visibility.PRIVATE, Ownership.STATIC) + .withParameters(clazz, Object[].class) + .intercept( + new SetFieldChunkInstruction(types, start, end, typeConversionsFactory)); + } + builder = + builder + .method(ElementMatchers.named("create")) + .intercept(new ChunkedSetFieldCreateInstruction(clazz, chunkCount)); + } return builder .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) @@ -326,12 +353,54 @@ public static SchemaUserTypeCreator createStaticCreator( DynamicType.Builder> builder, FieldValueTypeInformation typeInformation, TypeConversionsFactory typeConversionsFactory) { - return builder - .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) - .method(ElementMatchers.named("name")) - .intercept(FixedValue.reference(typeInformation.getName())) - .method(ElementMatchers.named("get")) - .intercept(new ReadFieldInstruction(typeInformation, typeConversionsFactory)); + builder = + builder + .method(ElementMatchers.named("name")) + .intercept(FixedValue.reference(typeInformation.getName())) + .method(ElementMatchers.named("get")) + .intercept(new ReadFieldInstruction(typeInformation, typeConversionsFactory)); + if (typeConversionsFactory.getClass() == ByteBuddyUtils.DefaultTypeConversionsFactory.class + && ByteBuddyUtils.inferredLogicalTypeFor(typeInformation.getRawType()) != null) { + builder = + builder + .implement(ByteBuddyUtils.DirectLogicalTypeGetter.class) + .method(ElementMatchers.named("getRaw")) + .intercept(new ReadRawFieldInstruction(typeInformation)); + } + return builder; + } + + // Reads the raw POJO field directly without logical-type toBaseType conversion. + private static class ReadRawFieldInstruction implements Implementation { + private final FieldValueTypeInformation typeInformation; + + ReadRawFieldInstruction(FieldValueTypeInformation typeInformation) { + this.typeInformation = typeInformation; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(final Target implementationTarget) { + return (methodVisitor, implementationContext, instrumentedMethod) -> { + int numLocals = 1 + instrumentedMethod.getParameters().size(); + StackManipulation cast = + typeInformation.getRawType().isAssignableFrom(typeInformation.getField().getType()) + ? StackManipulation.Trivial.INSTANCE + : TypeCasting.to(TypeDescription.ForLoadedType.of(typeInformation.getRawType())); + StackManipulation stackManipulation = + new StackManipulation.Compound( + MethodVariableAccess.REFERENCE.loadFrom(1), + FieldAccess.forField(new ForLoadedField(typeInformation.getField())).read(), + cast, + MethodReturn.REFERENCE); + StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext); + return new Size(size.getMaximalSize(), numLocals); + }; + } } // Implements a method to read a public field out of an object. @@ -505,4 +574,110 @@ public ByteCodeAppender appender(final Target implementationTarget) { }; } } + + // Instantiates a wide POJO and delegates field population to private static chunk helpers. + private static final class ChunkedSetFieldCreateInstruction implements Implementation { + private final Class pojoClass; + private final int chunkCount; + + ChunkedSetFieldCreateInstruction(Class pojoClass, int chunkCount) { + this.pojoClass = pojoClass; + this.chunkCount = chunkCount; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(final Target implementationTarget) { + return (mv, implementationContext, instrumentedMethod) -> { + String ownerInternal = implementationTarget.getInstrumentedType().getInternalName(); + String chunkDesc = + "(" + net.bytebuddy.jar.asm.Type.getDescriptor(pojoClass) + "[Ljava/lang/Object;)V"; + // Slots: 0=this, 1=params, 2=pojoInstance + // Resolve the zero-arg constructor via ByteBuddy identically to SetFieldCreateInstruction + // so missing no-arg constructors fail at generation time with IllegalStateException + // (wrapped by createSetFieldCreator into its descriptive RuntimeException). + ForLoadedType loadedType = new ForLoadedType(pojoClass); + new StackManipulation.Compound( + TypeCreation.of(loadedType), + Duplication.SINGLE, + MethodInvocation.invoke( + loadedType + .getDeclaredMethods() + .filter( + ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) + .getOnly())) + .apply(mv, implementationContext); + mv.visitVarInsn(Opcodes.ASTORE, 2); + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, ownerInternal, "setChunk" + c, chunkDesc, false); + } + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + return new Size(2, 3); + }; + } + } + + // Populates a slice [start, end) of public POJO fields inside a private static chunk method. + private static final class SetFieldChunkInstruction implements Implementation { + private final List typeInformations; + private final int start; + private final int end; + private final TypeConversionsFactory typeConversionsFactory; + + SetFieldChunkInstruction( + List typeInformations, + int start, + int end, + TypeConversionsFactory typeConversionsFactory) { + this.typeInformations = typeInformations; + this.start = start; + this.end = end; + this.typeConversionsFactory = typeConversionsFactory; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(final Target implementationTarget) { + return (methodVisitor, implementationContext, instrumentedMethod) -> { + // Static method slots: 0=pojoInstance, 1=params + int numLocals = 2; + TypeConversion convertType = typeConversionsFactory.createTypeConversion(true); + List ops = new ArrayList<>((end - start) + 1); + for (int i = start; i < end; ++i) { + FieldValueTypeInformation typeInformation = typeInformations.get(i); + Field field = typeInformation.getField(); + ForLoadedType convertedType = + new ForLoadedType((Class) convertType.convert(typeInformation.getType())); + StackManipulation readParameter = + new StackManipulation.Compound( + MethodVariableAccess.REFERENCE.loadFrom(1), + IntegerConstant.forValue(i), + ArrayAccess.REFERENCE.load(), + TypeCasting.to(convertedType)); + ops.add( + new StackManipulation.Compound( + MethodVariableAccess.REFERENCE.loadFrom(0), + typeConversionsFactory + .createSetterConversions(readParameter) + .convert(typeInformation.getType()), + FieldAccess.forField(new ForLoadedField(field)).write())); + } + ops.add(MethodReturn.VOID); + StackManipulation.Size size = + new StackManipulation.Compound(ops).apply(methodVisitor, implementationContext); + return new Size(size.getMaximalSize(), numLocals); + }; + } + } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ReflectUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ReflectUtils.java index 423fea4c3845..56b9d9e7c1f6 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ReflectUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/ReflectUtils.java @@ -32,6 +32,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.annotations.SchemaCreate; @@ -76,7 +77,10 @@ public static TypeDescriptorWithSchema create( } private static final Map, List> DECLARED_METHODS = Maps.newConcurrentMap(); - private static final Map, Method> ANNOTATED_CONSTRUCTORS = Maps.newConcurrentMap(); + private static final Map, Optional> ANNOTATED_CREATE_METHODS = + Maps.newConcurrentMap(); + private static final Map, Optional>> ANNOTATED_CONSTRUCTORS = + Maps.newConcurrentMap(); private static final Map, List> DECLARED_FIELDS = Maps.newConcurrentMap(); /** @@ -112,35 +116,41 @@ public static Multimap getMethodsMap(Class clazz) { } public static @Nullable Constructor getAnnotatedConstructor(Class clazz) { - return Arrays.stream(clazz.getDeclaredConstructors()) - .filter(m -> !Modifier.isPrivate(m.getModifiers())) - .filter(m -> !Modifier.isProtected(m.getModifiers())) - .filter(m -> m.getAnnotation(SchemaCreate.class) != null) - .findFirst() + return ANNOTATED_CONSTRUCTORS + .computeIfAbsent( + clazz, + c -> + Arrays.stream(c.getDeclaredConstructors()) + .filter(m -> !Modifier.isPrivate(m.getModifiers())) + .filter(m -> !Modifier.isProtected(m.getModifiers())) + .filter(m -> m.getAnnotation(SchemaCreate.class) != null) + .findFirst()) .orElse(null); } public static @Nullable Method getAnnotatedCreateMethod(Class clazz) { - return ANNOTATED_CONSTRUCTORS.computeIfAbsent( - clazz, - c -> { - Method method = - Arrays.stream(clazz.getDeclaredMethods()) - .filter(m -> !Modifier.isPrivate(m.getModifiers())) - .filter(m -> !Modifier.isProtected(m.getModifiers())) - .filter(m -> Modifier.isStatic(m.getModifiers())) - .filter(m -> m.getAnnotation(SchemaCreate.class) != null) - .findFirst() - .orElse(null); - if (method != null && !clazz.isAssignableFrom(method.getReturnType())) { - throw new InvalidParameterException( - "A method marked with SchemaCreate in class " - + clazz - + " does not return a type assignable to " - + clazz); - } - return method; - }); + return ANNOTATED_CREATE_METHODS + .computeIfAbsent( + clazz, + c -> { + Method method = + Arrays.stream(c.getDeclaredMethods()) + .filter(m -> !Modifier.isPrivate(m.getModifiers())) + .filter(m -> !Modifier.isProtected(m.getModifiers())) + .filter(m -> Modifier.isStatic(m.getModifiers())) + .filter(m -> m.getAnnotation(SchemaCreate.class) != null) + .findFirst() + .orElse(null); + if (method != null && !c.isAssignableFrom(method.getReturnType())) { + throw new InvalidParameterException( + "A method marked with SchemaCreate in class " + + c + + " does not return a type assignable to " + + c); + } + return Optional.ofNullable(method); + }) + .orElse(null); } // Get all public, non-static, non-transient fields. From 81232e9352f9f3c8e0278a05420c9c63d6df6038 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:53:16 -0800 Subject: [PATCH 04/15] Add RowWireCodec and optimize RowCoderGenerator with unrolled/chunked codecs and lazy byte-size observation Eliminates per-row allocation, megamorphic coder dispatch, and full re-encoding during byte-size observation while preserving 100% beam:coder:row:v1 wire compatibility: - RowWireCodec: shared buffered single-flush wire engine using re-entrancy-safe ScratchPool (MAX_DEPTH=8) and GC-safe RefScratchPool, byte-array VarHandles (SHORT_BE/INT_BE/INT_LE/LONG_BE), unrolled VarInt/5-byte VarLong readers, single-pass 8-fields/byte wide null bitmaps, and direct wire/size codecs for 29 field kinds. - RowCoderGenerator: monomorphic GeneratedRowCoder with 1..64 unrolled and 65..1024 32-field chunked RowFieldCodec (unlocked generation, weighted Metaspace cap of 512, omitted dead chunk families, direct mask==0 dispatch, needsDecodeScratch skip), >1024 zero-alloc wide-bitmap loop fallback, and O(1)/lazy ElementByteSizeObservableIterable byte-size observation. - SchemaCoderHelpers / SchemaCoder / RowCoder: direct wire/size LogicalTypeCoders, PassThroughLogicalType unwrapping, volatile delegateCoder, and byte-size observer delegation. --- .../org/apache/beam/sdk/coders/RowCoder.java | 3 +- .../beam/sdk/coders/RowCoderGenerator.java | 3042 +++++++++++++++-- .../apache/beam/sdk/coders/RowWireCodec.java | 2267 ++++++++++++ .../apache/beam/sdk/schemas/SchemaCoder.java | 24 +- .../beam/sdk/schemas/SchemaCoderHelpers.java | 420 ++- 5 files changed, 5406 insertions(+), 350 deletions(-) create mode 100644 sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowWireCodec.java diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoder.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoder.java index a8ff3b397fcd..fc3cbbe9a101 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoder.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoder.java @@ -18,7 +18,6 @@ package org.apache.beam.sdk.coders; import java.util.Map; -import java.util.Objects; import java.util.UUID; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.SchemaCoder; @@ -67,6 +66,6 @@ public boolean equals(@Nullable Object o) { @Override public int hashCode() { - return Objects.hash(schema); + return 31 + schema.hashCode(); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoderGenerator.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoderGenerator.java index dc6a28fdf6b8..befce8bd344d 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoderGenerator.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowCoderGenerator.java @@ -23,97 +23,280 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.Arrays; -import java.util.BitSet; +import java.util.Collection; +import java.util.List; import java.util.Map; +import java.util.RandomAccess; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import net.bytebuddy.ByteBuddy; -import net.bytebuddy.description.modifier.FieldManifestation; +import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.modifier.Ownership; import net.bytebuddy.description.modifier.Visibility; -import net.bytebuddy.description.type.TypeDescription; -import net.bytebuddy.description.type.TypeDescription.ForLoadedType; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.scaffold.InstrumentedType; import net.bytebuddy.implementation.FixedValue; import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.bytecode.ByteCodeAppender; -import net.bytebuddy.implementation.bytecode.ByteCodeAppender.Size; -import net.bytebuddy.implementation.bytecode.Duplication; -import net.bytebuddy.implementation.bytecode.StackManipulation; -import net.bytebuddy.implementation.bytecode.member.FieldAccess; -import net.bytebuddy.implementation.bytecode.member.MethodInvocation; -import net.bytebuddy.implementation.bytecode.member.MethodReturn; -import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess; +import net.bytebuddy.jar.asm.ClassWriter; +import net.bytebuddy.jar.asm.Label; +import net.bytebuddy.jar.asm.MethodVisitor; +import net.bytebuddy.jar.asm.Opcodes; import net.bytebuddy.matcher.ElementMatchers; +import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.schemas.Schema; -import org.apache.beam.sdk.schemas.Schema.Field; import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.Schema.LogicalType; +import org.apache.beam.sdk.schemas.Schema.TypeName; import org.apache.beam.sdk.schemas.SchemaCoder; +import org.apache.beam.sdk.schemas.logicaltypes.Date; +import org.apache.beam.sdk.schemas.logicaltypes.DateTime; +import org.apache.beam.sdk.schemas.logicaltypes.MicrosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.NanosDuration; +import org.apache.beam.sdk.schemas.logicaltypes.NanosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.Time; +import org.apache.beam.sdk.schemas.logicaltypes.UuidLogicalType; +import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.InjectPackageStrategy; import org.apache.beam.sdk.util.StringUtils; +import org.apache.beam.sdk.util.VarInt; +import org.apache.beam.sdk.util.common.ElementByteSizeObservableIterable; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.sdk.util.common.ReflectHelpers; import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; +import org.joda.time.ReadableInstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * A utility for automatically generating a {@link Coder} for {@link Row} objects corresponding to a - * specific schema. The resulting coder is loaded into the default ClassLoader and returned. + * Generates and caches a fast {@link Coder} for {@link Row} objects matching the {@code + * beam:coder:row:v1} wire format for a specific {@link Schema}. * - *

When {@link RowCoderGenerator#generate(Schema)} is called, a new subclass of {@literal - * Coder} is generated for the specified schema. This class is generated using low-level - * bytecode generation, and hardcodes encodings for all fields of the Schema. Empirically, this is - * 30-40% faster than a coder that introspects the schema. - * - *

The generated class corresponds to the following Java class: - * - *


- * class SchemaRowCoder extends{@literal Coder} {
- *   // Generated array containing a coder for each field in the Schema.
- *   private static final Coder[] FIELD_CODERS;
- *
- *   // Generated method to return the schema this class corresponds to. Used during code
- *   // generation.
- *   private static getSchema() {
- *     return schema;
- *   }
- *
- *  {@literal @}Override
- *   public void encode(T value, OutputStream outStream) {
- *     // Delegate to a method that evaluates each coder in the static array.
- *     encodeDelegate(FIELD_CODERS, value, outStream);
- *   }
- *
- *  {@literal @}Override
- *   public abstract T decode(InputStream inStream) {
- *     // Delegate to a method that evaluates each coder in the static array.
- *     return decodeDelegate(FIELD_CODERS, inStream);
- *   }
- * }
- * 
+ *

For schemas with {@code 1 <= fieldCount <= 64}, emits a straight-line unrolled {@link + * RowFieldCodec} via ByteBuddy so the JVM sees monomorphic field reads/writes with no per-field + * switch dispatch or branch misprediction. For wider schemas ({@code 65 <= fieldCount <= 1024}), + * emits chunked 32-field static helper methods on a single generated {@link RowFieldCodec} so every + * method stays well below HotSpot C2's 8KB {@code HugeMethodLimit} while avoiding switch dispatch. + * Schemas beyond {@code 1024} fields (or beyond the hard Metaspace budget) execute the shared + * buffered fallback loop powered by {@link RowWireCodec}. */ @SuppressWarnings({ "nullness", // TODO(https://github.com/apache/beam/issues/20497) "rawtypes" }) public abstract class RowCoderGenerator { + private static final Object[] EMPTY_VALUES = new Object[0]; + private static final int MAX_UNROLLED_FIELDS = 64; + private static final int MAX_CHUNKED_FIELDS = 1024; + private static final int CHUNK_SIZE = 32; + // Weighted Metaspace budget: <= 64-field single-method shapes cost 1; wide chunked shapes cost + // chunkCount (3..32) so wide generated classes cannot silently multiply Metaspace usage. + private static final int MAX_GENERATED_FIELD_CODEC_WEIGHT = 512; + + private static final String ROW_WIRE_CODEC = "org/apache/beam/sdk/coders/RowWireCodec"; + private static final String SCRATCH_POOL = "org/apache/beam/sdk/coders/RowWireCodec$ScratchPool"; + private static final String SCRATCH_POOL_DESC = + "Lorg/apache/beam/sdk/coders/RowWireCodec$ScratchPool;"; + private static final String CODER_TYPE = "org/apache/beam/sdk/coders/Coder"; + private static final String ROW_TYPE = "org/apache/beam/sdk/values/Row"; + private static final String OUT_DESC = "Ljava/io/OutputStream;"; + private static final String IN_DESC = "Ljava/io/InputStream;"; + private static final String CODER_DESC = "Lorg/apache/beam/sdk/coders/Coder;"; + + // Compact type tags for fast switch fallback and ByteBuddy unrolled field codec dispatch. + private static final byte KIND_BYTE = 0; + private static final byte KIND_INT16 = 1; + private static final byte KIND_INT32 = 2; + private static final byte KIND_INT64 = 3; + private static final byte KIND_FLOAT = 4; + private static final byte KIND_DOUBLE = 5; + private static final byte KIND_BOOLEAN = 6; + private static final byte KIND_DATETIME = 7; + private static final byte KIND_STRING = 8; + private static final byte KIND_BYTES = 9; + private static final byte KIND_ROW = 10; + private static final byte KIND_DECIMAL = 11; + private static final byte KIND_OTHER = 12; + private static final byte KIND_DATE = 13; + private static final byte KIND_TIME = 14; + private static final byte KIND_LOCAL_DATETIME = 15; + private static final byte KIND_UUID = 16; + private static final byte KIND_MICROS_INSTANT = 17; + private static final byte KIND_NANOS_INSTANT = 18; + private static final byte KIND_NANOS_DURATION = 19; + private static final byte KIND_STRING_LIST = 20; + private static final byte KIND_INT32_LIST = 21; + private static final byte KIND_INT64_LIST = 22; + private static final byte KIND_DOUBLE_LIST = 23; + private static final byte KIND_ROW_LIST = 24; + private static final byte KIND_STRING_LONG_MAP = 25; + private static final byte KIND_STRING_STRING_MAP = 26; + private static final byte KIND_STRING_INT_MAP = 27; + private static final byte KIND_STRING_DOUBLE_MAP = 28; + private static final ByteBuddy BYTE_BUDDY = new ByteBuddy(); - private static final BitSetCoder NULL_LIST_CODER = BitSetCoder.of(); - private static final VarIntCoder VAR_INT_CODER = VarIntCoder.of(); - // BitSet.get(n) will return false for any n >= nbits, so a BitSet with 0 bits will return false - // for all calls to get. - private static final BitSet EMPTY_BIT_SET = new BitSet(0); - private static final String CODERS_FIELD_NAME = "FIELD_CODERS"; - private static final String POSITIONS_FIELD_NAME = "FIELD_ENCODING_POSITIONS"; - private static final String SCHEMA_OPTION_STATIC_ENCODING = "beam:option:row:static_encoding"; + // Bounded non-evicting cache so classes defined into RowCoderGenerator's ClassLoader never + // thrash Metaspace; shapes beyond MAX_GENERATED_FIELD_CODEC_WEIGHT fall back cleanly to the + // buffered switch loop. + private static final ConcurrentHashMap FIELD_CODEC_CACHE = + new ConcurrentHashMap<>(); + private static final AtomicInteger GENERATED_FIELD_CODEC_WEIGHT = new AtomicInteger(); + + /** Base class for unrolled and chunked stateless per-shape ByteBuddy row field codecs. */ + @Internal + public abstract static class RowFieldCodec { + public void encodeArrayNoNulls( + Object[] values, + OutputStream out, + Coder[] coders, + Coder[] elemCoders, + boolean staticEncoding) + throws IOException { + throw new UnsupportedOperationException(); + } + + public void encodeArrayNullable( + Object[] values, OutputStream out, Coder[] coders, Coder[] elemCoders) throws IOException { + throw new UnsupportedOperationException(); + } + + public void encodeListNoNulls( + List values, + OutputStream out, + Coder[] coders, + Coder[] elemCoders, + boolean staticEncoding) + throws IOException { + throw new UnsupportedOperationException(); + } + + public void encodeListNullable( + List values, OutputStream out, Coder[] coders, Coder[] elemCoders) + throws IOException { + throw new UnsupportedOperationException(); + } + + public void encodeRowNoNulls( + Row row, OutputStream out, Coder[] coders, Coder[] elemCoders, boolean staticEncoding) + throws IOException { + throw new UnsupportedOperationException(); + } + + public Object[] decodeNoNulls(InputStream in, Coder[] coders, Coder[] elemCoders) + throws IOException { + throw new UnsupportedOperationException(); + } + + public Object[] decodeNullable( + InputStream in, Coder[] coders, Coder[] elemCoders, long nullMask, byte[] buf) + throws IOException { + throw new UnsupportedOperationException(); + } + + public int encodeArrayBody( + Object[] values, OutputStream out, Coder[] coders, Coder[] elemCoders, byte[] buf, int pos) + throws IOException { + throw new UnsupportedOperationException(); + } + + public int encodeListBody( + List values, + OutputStream out, + Coder[] coders, + Coder[] elemCoders, + byte[] buf, + int pos) + throws IOException { + throw new UnsupportedOperationException(); + } + + public boolean supportsRowBody() { + return false; + } + + public boolean supportsNullableWideDecode() { + return false; + } + + public int encodeRowBody( + Row row, OutputStream out, Coder[] coders, Coder[] elemCoders, byte[] buf, int pos) + throws IOException { + throw new UnsupportedOperationException(); + } + + public Object[] decodeNoNullsWide( + InputStream in, Coder[] coders, Coder[] elemCoders, byte[] buf) throws IOException { + throw new UnsupportedOperationException(); + } + + public Object[] decodeNullableWide( + InputStream in, + Coder[] coders, + Coder[] elemCoders, + byte[] nullBytes, + int nullByteLen, + byte[] buf) + throws IOException { + throw new UnsupportedOperationException(); + } + } + + private static final class CodecShapeKey { + final byte[] fieldKinds; + final int[] encodingPosToIndex; + final boolean includeNullableDecode; + final boolean includeRowBody; + final int hash; + + CodecShapeKey( + byte[] fieldKinds, + int[] encodingPosToIndex, + boolean includeNullableDecode, + boolean includeRowBody) { + this.fieldKinds = fieldKinds; + this.encodingPosToIndex = encodingPosToIndex; + this.includeNullableDecode = includeNullableDecode; + this.includeRowBody = includeRowBody; + int h = 31 * Arrays.hashCode(fieldKinds) + Arrays.hashCode(encodingPosToIndex); + h = 31 * h + (includeNullableDecode ? 1 : 0); + h = 31 * h + (includeRowBody ? 1 : 0); + this.hash = h; + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CodecShapeKey)) { + return false; + } + CodecShapeKey that = (CodecShapeKey) o; + return hash == that.hash + && includeNullableDecode == that.includeNullableDecode + && includeRowBody == that.includeRowBody + && Arrays.equals(fieldKinds, that.fieldKinds) + && Arrays.equals(encodingPosToIndex, that.encodingPosToIndex); + } + } static class WithStackTrace { private final T value; @@ -133,7 +316,7 @@ public String getStackTrace() { } } - // Cache for Coder class that are already generated. + // Cache for Coder instances that are already constructed. @GuardedBy("cacheLock") private static final Map>> GENERATED_CODERS = Maps.newHashMap(); @@ -149,6 +332,89 @@ private static String getStackTrace() { return StringUtils.arrayToNewlines(Thread.currentThread().getStackTrace(), 10); } + /** Returns whether explicit encoding positions have been registered for the given schema UUID. */ + @Internal + public static boolean hasEncodingPositionOverride(@Nullable UUID uuid) { + if (uuid == null) { + return false; + } + synchronized (cacheLock) { + return ENCODING_POSITION_OVERRIDES.containsKey(uuid); + } + } + + /** + * Resolves the mapping {@code encodingPosition -> rowFieldIndex} for {@code schema}, honoring any + * registered {@link #overrideEncodingPositions} entry for {@code schema.getUUID()}. + */ + @Internal + public static int[] resolveEncodingPosToRowIndex(Schema schema) { + UUID uuid = Preconditions.checkNotNull(schema.getUUID()); + synchronized (cacheLock) { + return resolveEncodingPosToRowIndexLocked(schema, uuid); + } + } + + @GuardedBy("cacheLock") + private static int[] resolveEncodingPosToRowIndexLocked(Schema schema, UUID uuid) { + int fieldCount = schema.getFieldCount(); + int[] encodingPosToRowIndex = new int[fieldCount]; + @Nullable + WithStackTrace> existingEncodingPositions = + ENCODING_POSITION_OVERRIDES.get(uuid); + Map encodingPositions = + existingEncodingPositions == null + ? schema.getEncodingPositions() + : existingEncodingPositions.getValue(); + boolean identityPositions = true; + for (int recordIndex = 0; recordIndex < fieldCount; ++recordIndex) { + String name = schema.getField(recordIndex).getName(); + Integer pos = encodingPositions.get(name); + Preconditions.checkState( + pos != null, "Missing encoding position for field %s in schema %s", name, uuid); + int encodingPosition = pos; + encodingPosToRowIndex[encodingPosition] = recordIndex; + if (encodingPosition != recordIndex) { + identityPositions = false; + } + } + if (!identityPositions) { + Preconditions.checkState( + fieldCount == Arrays.stream(encodingPosToRowIndex).distinct().count()); + } + return encodingPosToRowIndex; + } + + /** + * Decodes the remainder of a {@code beam:coder:row:v1} stream after {@code streamFieldCount} has + * already been consumed. Used by direct schema coders on schema-evolution fallback paths. + */ + @Internal + public static Row decodeAfterFieldCount( + Coder delegateCoder, int streamFieldCount, InputStream inStream) throws IOException { + if (!(delegateCoder instanceof GeneratedRowCoder)) { + throw new CoderException("Unexpected delegate row coder type: " + delegateCoder); + } + int nullByteLen = RowWireCodec.readVarInt(inStream); + return ((GeneratedRowCoder) delegateCoder) + .decodeAfterNullByteLen(streamFieldCount, nullByteLen, inStream); + } + + /** + * Decodes the remainder of a {@code beam:coder:row:v1} stream after both {@code streamFieldCount} + * and {@code nullByteLen} have already been consumed. + */ + @Internal + public static Row decodeAfterNullByteLen( + Coder delegateCoder, int streamFieldCount, int nullByteLen, InputStream inStream) + throws IOException { + if (!(delegateCoder instanceof GeneratedRowCoder)) { + throw new CoderException("Unexpected delegate row coder type: " + delegateCoder); + } + return ((GeneratedRowCoder) delegateCoder) + .decodeAfterNullByteLen(streamFieldCount, nullByteLen, inStream); + } + public static void overrideEncodingPositions(UUID uuid, Map encodingPositions) { final String stackTrace = getStackTrace(); synchronized (cacheLock) { @@ -198,363 +464,2465 @@ static void clearRowCoderCache() { } } - @SuppressWarnings("unchecked") + @GuardedBy("cacheLock") + private static boolean canUseDirectRowEncodingLocked(@Nullable Schema rowSchema) { + if (rowSchema == null) { + return false; + } + if (rowSchema.isEncodingPositionsOverridden() || rowSchema.isStaticEncoding()) { + return false; + } + UUID id = rowSchema.getUUID(); + if (id == null) { + return true; + } + return !ENCODING_POSITION_OVERRIDES.containsKey(id); + } + public static Coder generate(Schema schema) { UUID uuid = Preconditions.checkNotNull(schema.getUUID()); + int fieldCount; + int[] encodingPosToRowIndex; + boolean identityPositions; + boolean hasNullableFields; + Coder[] componentCoders; + Coder[] elemCoders; + boolean hasRowList; + byte[] fieldKinds; + long fixedPayloadSize; + // Avoid using computeIfAbsent which may cause issues with nested schemas. synchronized (cacheLock) { @Nullable WithStackTrace> existingRowCoder = GENERATED_CODERS.get(uuid); if (existingRowCoder != null) { return existingRowCoder.getValue(); } - TypeDescription.Generic coderType = - TypeDescription.Generic.Builder.parameterizedType(Coder.class, Row.class).build(); - DynamicType.Builder builder = - (DynamicType.Builder) BYTE_BUDDY.subclass(coderType); - builder = implementMethods(schema, builder); - int[] encodingPosToRowIndex = new int[schema.getFieldCount()]; - @Nullable - WithStackTrace> existingEncodingPositions = - ENCODING_POSITION_OVERRIDES.get(uuid); - Map encodingPositions = - existingEncodingPositions == null - ? schema.getEncodingPositions() - : existingEncodingPositions.getValue(); - for (int recordIndex = 0; recordIndex < schema.getFieldCount(); ++recordIndex) { - String name = schema.getField(recordIndex).getName(); - int encodingPosition = encodingPositions.get(name); - encodingPosToRowIndex[encodingPosition] = recordIndex; - } - // There should never be duplicate encoding positions. - Preconditions.checkState( - schema.getFieldCount() == Arrays.stream(encodingPosToRowIndex).distinct().count()); + fieldCount = schema.getFieldCount(); + encodingPosToRowIndex = resolveEncodingPosToRowIndexLocked(schema, uuid); + identityPositions = true; + for (int i = 0; i < fieldCount; i++) { + if (encodingPosToRowIndex[i] != i) { + identityPositions = false; + break; + } + } + + hasNullableFields = schema.hasNullableFields(); + componentCoders = new Coder[fieldCount]; + elemCoders = new Coder[fieldCount]; + hasRowList = false; + fieldKinds = new byte[fieldCount]; + fixedPayloadSize = hasNullableFields ? -1L : 0L; - // Component coders are ordered by encoding position, but may encode a field with a different - // row index. - Coder[] componentCoders = new Coder[schema.getFieldCount()]; - for (int i = 0; i < schema.getFieldCount(); ++i) { + for (int i = 0; i < fieldCount; ++i) { int rowIndex = encodingPosToRowIndex[i]; - // We use withNullable(false) as nulls are handled by the RowCoder and the individual - // component coders therefore do not need to handle nulls. - componentCoders[i] = - SchemaCoder.coderForFieldType(schema.getField(rowIndex).getType().withNullable(false)); + FieldType fieldType = schema.getField(rowIndex).getType(); + byte kind = fieldKindForFieldTypeLocked(fieldType); + fieldKinds[i] = kind; + if (kind == KIND_ROW) { + Schema nestedRowSchema = fieldType.getRowSchema(); + if (nestedRowSchema != null && nestedRowSchema.getUUID() != null) { + componentCoders[i] = generate(nestedRowSchema); + } else { + // Preserve SchemaCoder.of() behavior of cloning & assigning UUIDs to nested schemas. + componentCoders[i] = SchemaCoder.coderForFieldType(fieldType.withNullable(false)); + } + } else { + // Nulls are handled by RowCoderGenerator's null bitmap, so use withNullable(false). + componentCoders[i] = SchemaCoder.coderForFieldType(fieldType.withNullable(false)); + if (kind == KIND_ROW_LIST) { + Schema elemRowSchema = fieldType.getCollectionElementType().getRowSchema(); + if (elemRowSchema != null && elemRowSchema.getUUID() != null) { + elemCoders[i] = generate(elemRowSchema); + hasRowList = true; + } else { + fieldKinds[i] = KIND_OTHER; + } + } + } + + if (fixedPayloadSize >= 0L) { + int fixed = fixedByteSizeForKind(kind); + if (fixed >= 0) { + fixedPayloadSize += fixed; + } else { + fixedPayloadSize = -1L; + } + } } + } + + // Generate or look up the stateless ByteBuddy RowFieldCodec outside cacheLock so concurrent + // callers (and cache hits in GENERATED_CODERS) are never blocked during COMPUTE_FRAMES. + @Nullable RowFieldCodec fieldCodec = null; + if (fieldCount >= 1 && fieldCount <= MAX_CHUNKED_FIELDS) { + boolean includeNullableDecode = fieldCount <= MAX_UNROLLED_FIELDS || hasNullableFields; + boolean includeRowBody = + fieldCount <= MAX_UNROLLED_FIELDS || !hasNullableFields || schema.isStaticEncoding(); + fieldCodec = + getOrGenerateFieldCodec( + fieldKinds, encodingPosToRowIndex, includeNullableDecode, includeRowBody); + } + Coder rowCoder = + new GeneratedRowCoder( + schema, + componentCoders, + hasRowList ? elemCoders : null, + fieldKinds, + encodingPosToRowIndex, + hasNullableFields, + identityPositions, + fixedPayloadSize, + fieldCodec); + + synchronized (cacheLock) { + @Nullable WithStackTrace> existingRowCoder = GENERATED_CODERS.get(uuid); + if (existingRowCoder != null) { + return existingRowCoder.getValue(); + } + String stackTrace = LOG.isDebugEnabled() ? getStackTrace() : ""; + GENERATED_CODERS.put(uuid, new WithStackTrace<>(rowCoder, stackTrace)); + if (LOG.isDebugEnabled()) { + LOG.debug("Created row coder for uuid {} at {}", uuid, stackTrace); + } + return rowCoder; + } + } + + @GuardedBy("cacheLock") + private static byte fieldKindForFieldTypeLocked(FieldType fieldType) { + TypeName typeName = fieldType.getTypeName(); + switch (typeName) { + case BYTE: + return KIND_BYTE; + case INT16: + return KIND_INT16; + case INT32: + return KIND_INT32; + case INT64: + return KIND_INT64; + case FLOAT: + return KIND_FLOAT; + case DOUBLE: + return KIND_DOUBLE; + case BOOLEAN: + return KIND_BOOLEAN; + case DATETIME: + return KIND_DATETIME; + case STRING: + return KIND_STRING; + case BYTES: + return KIND_BYTES; + case ROW: + return KIND_ROW; + case DECIMAL: + return KIND_DECIMAL; + case LOGICAL_TYPE: + LogicalType logicalType = fieldType.getLogicalType(); + if (logicalType == null) { + return KIND_OTHER; + } + Class clazz = logicalType.getClass(); + if (clazz == Date.class) { + return KIND_DATE; + } + if (clazz == Time.class) { + return KIND_TIME; + } + if (clazz == DateTime.class && canUseDirectRowEncodingLocked(DateTime.DATETIME_SCHEMA)) { + return KIND_LOCAL_DATETIME; + } + if (clazz == UuidLogicalType.class + && canUseDirectRowEncodingLocked(UuidLogicalType.UUID_SCHEMA)) { + return KIND_UUID; + } + if (clazz == MicrosInstant.class + && canUseDirectRowEncodingLocked(logicalType.getBaseType().getRowSchema())) { + return KIND_MICROS_INSTANT; + } + if (clazz == NanosInstant.class + && canUseDirectRowEncodingLocked(logicalType.getBaseType().getRowSchema())) { + return KIND_NANOS_INSTANT; + } + if (clazz == NanosDuration.class + && canUseDirectRowEncodingLocked(logicalType.getBaseType().getRowSchema())) { + return KIND_NANOS_DURATION; + } + return KIND_OTHER; + case ARRAY: + case ITERABLE: + FieldType elemType = fieldType.getCollectionElementType(); + if (elemType == null || elemType.getNullable()) { + return KIND_OTHER; + } + switch (elemType.getTypeName()) { + case STRING: + return KIND_STRING_LIST; + case INT32: + return KIND_INT32_LIST; + case INT64: + return KIND_INT64_LIST; + case DOUBLE: + return KIND_DOUBLE_LIST; + case ROW: + return elemType.getRowSchema() != null ? KIND_ROW_LIST : KIND_OTHER; + default: + return KIND_OTHER; + } + case MAP: + FieldType keyType = fieldType.getMapKeyType(); + FieldType valueType = fieldType.getMapValueType(); + if (keyType == null + || valueType == null + || keyType.getNullable() + || valueType.getNullable() + || keyType.getTypeName() != TypeName.STRING) { + return KIND_OTHER; + } + switch (valueType.getTypeName()) { + case INT64: + return KIND_STRING_LONG_MAP; + case STRING: + return KIND_STRING_STRING_MAP; + case INT32: + return KIND_STRING_INT_MAP; + case DOUBLE: + return KIND_STRING_DOUBLE_MAP; + default: + return KIND_OTHER; + } + default: + return KIND_OTHER; + } + } + + private static int fixedByteSizeForKind(byte kind) { + switch (kind) { + case KIND_BYTE: + case KIND_BOOLEAN: + return 1; + case KIND_INT16: + return 2; + case KIND_FLOAT: + return 4; + case KIND_DOUBLE: + case KIND_DATETIME: + return 8; + default: + return -1; + } + } + + private static @Nullable RowFieldCodec getOrGenerateFieldCodec( + byte[] fieldKinds, + int[] encodingPosToRowIndex, + boolean includeNullableDecode, + boolean includeRowBody) { + CodecShapeKey key = + new CodecShapeKey(fieldKinds, encodingPosToRowIndex, includeNullableDecode, includeRowBody); + RowFieldCodec cached = FIELD_CODEC_CACHE.get(key); + if (cached != null) { + return cached; + } + int weight = + fieldKinds.length <= MAX_UNROLLED_FIELDS + ? 1 + : (fieldKinds.length + CHUNK_SIZE - 1) / CHUNK_SIZE; + if (GENERATED_FIELD_CODEC_WEIGHT.get() + weight > MAX_GENERATED_FIELD_CODEC_WEIGHT) { + return null; + } + return FIELD_CODEC_CACHE.computeIfAbsent( + key, + k -> { + if (GENERATED_FIELD_CODEC_WEIGHT.addAndGet(weight) > MAX_GENERATED_FIELD_CODEC_WEIGHT) { + GENERATED_FIELD_CODEC_WEIGHT.addAndGet(-weight); + return null; + } + try { + return generateFieldCodec( + k.fieldKinds, k.encodingPosToIndex, k.includeNullableDecode, k.includeRowBody); + } catch (Exception | LinkageError e) { + GENERATED_FIELD_CODEC_WEIGHT.addAndGet(-weight); + LOG.warn("Falling back to interpreted RowFieldCodec due to generation failure", e); + return null; + } + }); + } + + @Internal + @VisibleForTesting + public static boolean hasGeneratedFieldCodec(Coder coder) { + return (coder instanceof GeneratedRowCoder) && ((GeneratedRowCoder) coder).fieldCodec != null; + } + + private static RowFieldCodec generateFieldCodec( + byte[] fieldKinds, + int[] encodingPosToIndex, + boolean includeNullableDecode, + boolean includeRowBody) + throws Exception { + if (fieldKinds.length > MAX_UNROLLED_FIELDS) { + return generateChunkedFieldCodec( + fieldKinds, encodingPosToIndex, includeNullableDecode, includeRowBody); + } + DynamicType.Builder builder = + BYTE_BUDDY + .with(new InjectPackageStrategy(RowCoderGenerator.class)) + .subclass(RowFieldCodec.class) + .method(ElementMatchers.named("encodeArrayNoNulls")) + .intercept( + new EncodeFieldsImpl(fieldKinds, encodingPosToIndex, SourceKind.ARRAY, false)) + .method(ElementMatchers.named("encodeArrayNullable")) + .intercept(new EncodeFieldsImpl(fieldKinds, encodingPosToIndex, SourceKind.ARRAY, true)) + .method(ElementMatchers.named("encodeListNoNulls")) + .intercept(new EncodeFieldsImpl(fieldKinds, encodingPosToIndex, SourceKind.LIST, false)) + .method(ElementMatchers.named("encodeListNullable")) + .intercept(new EncodeFieldsImpl(fieldKinds, encodingPosToIndex, SourceKind.LIST, true)) + .method(ElementMatchers.named("encodeRowNoNulls")) + .intercept(new EncodeFieldsImpl(fieldKinds, encodingPosToIndex, SourceKind.ROW, false)) + .method(ElementMatchers.named("decodeNoNulls")) + .intercept(new DecodeImpl(fieldKinds, encodingPosToIndex, false)) + .method(ElementMatchers.named("decodeNullable")) + .intercept(new DecodeImpl(fieldKinds, encodingPosToIndex, true)); + + return builder + .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) + .make() + .load( + ReflectHelpers.findClassLoader(RowCoderGenerator.class.getClassLoader()), + getClassLoadingStrategy(RowCoderGenerator.class)) + .getLoaded() + .getDeclaredConstructor() + .newInstance(); + } + + private static RowFieldCodec generateChunkedFieldCodec( + byte[] fieldKinds, + int[] encodingPosToIndex, + boolean includeNullableDecode, + boolean includeRowBody) + throws Exception { + int count = fieldKinds.length; + int chunkCount = (count + CHUNK_SIZE - 1) / CHUNK_SIZE; + DynamicType.Builder builder = + BYTE_BUDDY + .with(new InjectPackageStrategy(RowCoderGenerator.class)) + .subclass(RowFieldCodec.class); + + for (int c = 0; c < chunkCount; c++) { + int start = c * CHUNK_SIZE; + int end = Math.min(start + CHUNK_SIZE, count); + // Parameter order puts hot locals (src=0, buf=1, pos=2, out=3) in 1-byte opcode slots. builder = builder - .defineField( - CODERS_FIELD_NAME, Coder[].class, Visibility.PRIVATE, FieldManifestation.FINAL) - .defineField( - POSITIONS_FIELD_NAME, int[].class, Visibility.PRIVATE, FieldManifestation.FINAL) - .defineConstructor(Modifier.PUBLIC) - .withParameters(Coder[].class, int[].class) - .intercept(new GeneratedCoderConstructor()); - - Coder rowCoder; - try { - rowCoder = + .defineMethod("encArrC" + c, int.class, Visibility.PRIVATE, Ownership.STATIC) + .withParameters( + Object[].class, + byte[].class, + int.class, + OutputStream.class, + Coder[].class, + Coder[].class) + .throwing(IOException.class) + .intercept( + new EncodeChunkImpl(fieldKinds, encodingPosToIndex, start, end, SourceKind.ARRAY)) + .defineMethod("encListC" + c, int.class, Visibility.PRIVATE, Ownership.STATIC) + .withParameters( + List.class, + byte[].class, + int.class, + OutputStream.class, + Coder[].class, + Coder[].class) + .throwing(IOException.class) + .intercept( + new EncodeChunkImpl(fieldKinds, encodingPosToIndex, start, end, SourceKind.LIST)) + .defineMethod("decNoNullC" + c, void.class, Visibility.PRIVATE, Ownership.STATIC) + .withParameters( + Object[].class, InputStream.class, Coder[].class, Coder[].class, byte[].class) + .throwing(IOException.class) + .intercept(new DecodeChunkImpl(fieldKinds, encodingPosToIndex, start, end, false)); + if (includeRowBody) { + builder = builder - .make() - .load( - ReflectHelpers.findClassLoader(Coder.class.getClassLoader()), - getClassLoadingStrategy(Coder.class)) - .getLoaded() - .getDeclaredConstructor(Coder[].class, int[].class) - .newInstance((Object) componentCoders, (Object) encodingPosToRowIndex); - } catch (InstantiationException - | IllegalAccessException - | NoSuchMethodException - | InvocationTargetException e) { - throw new RuntimeException("Unable to generate coder for schema " + schema, e); - } - String stackTrace = getStackTrace(); - GENERATED_CODERS.put(uuid, new WithStackTrace<>(rowCoder, stackTrace)); - LOG.debug( - "Created row coder for uuid {} with encoding positions {} at {}", - uuid, - encodingPositions, - stackTrace); - return rowCoder; + .defineMethod("encRowC" + c, int.class, Visibility.PRIVATE, Ownership.STATIC) + .withParameters( + Row.class, + byte[].class, + int.class, + OutputStream.class, + Coder[].class, + Coder[].class) + .throwing(IOException.class) + .intercept( + new EncodeChunkImpl( + fieldKinds, encodingPosToIndex, start, end, SourceKind.ROW)); + } + if (includeNullableDecode) { + builder = + builder + .defineMethod("decNullC" + c, void.class, Visibility.PRIVATE, Ownership.STATIC) + .withParameters( + Object[].class, + InputStream.class, + Coder[].class, + Coder[].class, + byte[].class, + int.class) + .throwing(IOException.class) + .intercept(new DecodeChunkImpl(fieldKinds, encodingPosToIndex, start, end, true)); + } + } + + builder = + builder + .method(ElementMatchers.named("encodeArrayBody")) + .intercept(new ChunkedEncodeDispatchImpl(chunkCount, SourceKind.ARRAY)) + .method(ElementMatchers.named("encodeListBody")) + .intercept(new ChunkedEncodeDispatchImpl(chunkCount, SourceKind.LIST)) + .method(ElementMatchers.named("decodeNoNullsWide")) + .intercept(new ChunkedDecodeDispatchImpl(count, chunkCount, false)); + if (includeRowBody) { + builder = + builder + .method(ElementMatchers.named("supportsRowBody")) + .intercept(FixedValue.value(true)) + .method(ElementMatchers.named("encodeRowBody")) + .intercept(new ChunkedEncodeDispatchImpl(chunkCount, SourceKind.ROW)); + } + if (includeNullableDecode) { + builder = + builder + .method(ElementMatchers.named("supportsNullableWideDecode")) + .intercept(FixedValue.value(true)) + .method(ElementMatchers.named("decodeNullableWide")) + .intercept(new ChunkedDecodeDispatchImpl(count, chunkCount, true)); + } + + return builder + .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) + .make() + .load( + ReflectHelpers.findClassLoader(RowCoderGenerator.class.getClassLoader()), + getClassLoadingStrategy(RowCoderGenerator.class)) + .getLoaded() + .getDeclaredConstructor() + .newInstance(); + } + + private static void pushInt(MethodVisitor mv, int value) { + if (value >= -1 && value <= 5) { + mv.visitInsn(Opcodes.ICONST_0 + value); + } else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + mv.visitIntInsn(Opcodes.BIPUSH, value); + } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) { + mv.visitIntInsn(Opcodes.SIPUSH, value); + } else { + mv.visitLdcInsn(value); + } + } + + private static final String PACK_SUFFIX = "[BI" + OUT_DESC + ")I"; + + /** Emits a buffered pack call for a non-null field value loaded in {@code valLocal}. */ + private static void emitPackFieldValue( + MethodVisitor mv, + byte kind, + int pos, + int valLocal, + int outLocal, + int codersLocal, + int elemCodersLocal, + int bufLocal, + int posLocal) { + switch (kind) { + case KIND_BYTE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Byte"); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B", false); + emitPackCall(mv, "packByte", "(B" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_INT16: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Short"); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S", false); + emitPackCall(mv, "packInt16", "(S" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_INT32: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer"); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); + emitPackCall(mv, "packVarInt", "(I" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_INT64: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Long"); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J", false); + emitPackCall(mv, "packVarLong", "(J" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_FLOAT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Float"); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F", false); + emitPackCall(mv, "packFloat", "(F" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Double"); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D", false); + emitPackCall(mv, "packDouble", "(D" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_BOOLEAN: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean"); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false); + emitPackCall(mv, "packBoolean", "(Z" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "org/joda/time/ReadableInstant"); + emitPackCall( + mv, + "packDateTime", + "(Lorg/joda/time/ReadableInstant;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_STRING: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/String"); + emitPackCall( + mv, "packString", "(Ljava/lang/String;" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_BYTES: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "[B"); + emitPackCall(mv, "packBytes", "([B" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_DECIMAL: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/math/BigDecimal"); + emitPackCall( + mv, + "packDecimal", + "(Ljava/math/BigDecimal;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_DATE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/time/LocalDate"); + emitPackCall( + mv, + "packLocalDate", + "(Ljava/time/LocalDate;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_TIME: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/time/LocalTime"); + emitPackCall( + mv, + "packLocalTime", + "(Ljava/time/LocalTime;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_LOCAL_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/time/LocalDateTime"); + emitPackCall( + mv, + "packLocalDateTime", + "(Ljava/time/LocalDateTime;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_UUID: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/UUID"); + emitPackCall( + mv, "packUuid", "(Ljava/util/UUID;" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case KIND_MICROS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/time/Instant"); + emitPackCall( + mv, + "packMicrosInstant", + "(Ljava/time/Instant;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_NANOS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/time/Instant"); + emitPackCall( + mv, + "packNanosInstant", + "(Ljava/time/Instant;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_NANOS_DURATION: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/time/Duration"); + emitPackCall( + mv, + "packNanosDuration", + "(Ljava/time/Duration;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case KIND_STRING_LIST: + emitPackIterableCall( + mv, "packStringIterable", pos, valLocal, bufLocal, posLocal, outLocal, codersLocal); + break; + case KIND_INT32_LIST: + emitPackIterableCall( + mv, "packInt32Iterable", pos, valLocal, bufLocal, posLocal, outLocal, codersLocal); + break; + case KIND_INT64_LIST: + emitPackIterableCall( + mv, "packInt64Iterable", pos, valLocal, bufLocal, posLocal, outLocal, codersLocal); + break; + case KIND_DOUBLE_LIST: + emitPackIterableCall( + mv, "packDoubleIterable", pos, valLocal, bufLocal, posLocal, outLocal, codersLocal); + break; + case KIND_ROW_LIST: + // Flush buffered bytes before calling nested row element coder. + emitFlush(mv, bufLocal, posLocal, outLocal); + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Iterable"); + mv.visitVarInsn(Opcodes.ALOAD, elemCodersLocal); + pushInt(mv, pos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitVarInsn(Opcodes.ALOAD, codersLocal); + pushInt(mv, pos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "writeElementIterable", + "(Ljava/lang/Iterable;" + CODER_DESC + OUT_DESC + CODER_DESC + ")V", + false); + break; + case KIND_STRING_LONG_MAP: + emitPackMapCall(mv, "packStringLongMap", valLocal, bufLocal, posLocal, outLocal); + break; + case KIND_STRING_STRING_MAP: + emitPackMapCall(mv, "packStringStringMap", valLocal, bufLocal, posLocal, outLocal); + break; + case KIND_STRING_INT_MAP: + emitPackMapCall(mv, "packStringIntMap", valLocal, bufLocal, posLocal, outLocal); + break; + case KIND_STRING_DOUBLE_MAP: + emitPackMapCall(mv, "packStringDoubleMap", valLocal, bufLocal, posLocal, outLocal); + break; + default: + // Flush buffered bytes before invoking nested/arbitrary Coder.encode. + emitFlush(mv, bufLocal, posLocal, outLocal); + mv.visitVarInsn(Opcodes.ALOAD, codersLocal); + pushInt(mv, pos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + CODER_TYPE, + "encode", + "(Ljava/lang/Object;" + OUT_DESC + ")V", + false); + break; } } - private static class GeneratedCoderConstructor implements Implementation { + private static void emitPackCall( + MethodVisitor mv, String method, String desc, int bufLocal, int posLocal, int outLocal) { + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitVarInsn(Opcodes.ILOAD, posLocal); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, method, desc, false); + mv.visitVarInsn(Opcodes.ISTORE, posLocal); + } + + private static void emitFlush(MethodVisitor mv, int bufLocal, int posLocal, int outLocal) { + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitVarInsn(Opcodes.ILOAD, posLocal); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "flush", "([BI" + OUT_DESC + ")I", false); + mv.visitVarInsn(Opcodes.ISTORE, posLocal); + } + + private static void emitPackIterableCall( + MethodVisitor mv, + String methodName, + int pos, + int valLocal, + int bufLocal, + int posLocal, + int outLocal, + int codersLocal) { + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Iterable"); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitVarInsn(Opcodes.ILOAD, posLocal); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitVarInsn(Opcodes.ALOAD, codersLocal); + pushInt(mv, pos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + methodName, + "(Ljava/lang/Iterable;[BI" + OUT_DESC + CODER_DESC + ")I", + false); + mv.visitVarInsn(Opcodes.ISTORE, posLocal); + } + + private static void emitPackMapCall( + MethodVisitor mv, String methodName, int valLocal, int bufLocal, int posLocal, int outLocal) { + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/Map"); + emitPackCall(mv, methodName, "(Ljava/util/Map;" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + } + + /** + * Pushes the decoded boxed/object field value onto the operand stack using hoisted {@code + * bufLocal}. + */ + private static void emitReadFieldValue( + MethodVisitor mv, + byte kind, + int pos, + int inLocal, + int codersLocal, + int elemCodersLocal, + int bufLocal) { + switch (kind) { + case KIND_BYTE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readByte", "(" + IN_DESC + ")B", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false); + break; + case KIND_INT16: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readInt16", "(" + IN_DESC + "[B)S", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false); + break; + case KIND_INT32: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); + break; + case KIND_INT64: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readVarLong", "(" + IN_DESC + ")J", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); + break; + case KIND_FLOAT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readFloat", "(" + IN_DESC + "[B)F", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false); + break; + case KIND_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readDouble", "(" + IN_DESC + "[B)D", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false); + break; + case KIND_BOOLEAN: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readBoolean", "(" + IN_DESC + ")Z", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); + break; + case KIND_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readDateTime", + "(" + IN_DESC + "[B)Lorg/joda/time/Instant;", + false); + break; + case KIND_STRING: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readString", + "(" + IN_DESC + "[B)Ljava/lang/String;", + false); + break; + case KIND_BYTES: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "readBytes", "(" + IN_DESC + ")[B", false); + break; + case KIND_DECIMAL: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readDecimal", + "(" + IN_DESC + "[B)Ljava/math/BigDecimal;", + false); + break; + case KIND_DATE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readLocalDate", + "(" + IN_DESC + ")Ljava/time/LocalDate;", + false); + break; + case KIND_TIME: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readLocalTime", + "(" + IN_DESC + ")Ljava/time/LocalTime;", + false); + break; + case KIND_LOCAL_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readLocalDateTime", + "(" + IN_DESC + ")Ljava/time/LocalDateTime;", + false); + break; + case KIND_UUID: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readUuid", + "(" + IN_DESC + ")Ljava/util/UUID;", + false); + break; + case KIND_MICROS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readMicrosInstant", + "(" + IN_DESC + ")Ljava/time/Instant;", + false); + break; + case KIND_NANOS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readNanosInstant", + "(" + IN_DESC + ")Ljava/time/Instant;", + false); + break; + case KIND_NANOS_DURATION: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readNanosDuration", + "(" + IN_DESC + ")Ljava/time/Duration;", + false); + break; + case KIND_STRING_LIST: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readStringList", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + break; + case KIND_INT32_LIST: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readInt32List", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + break; + case KIND_INT64_LIST: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readInt64List", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + break; + case KIND_DOUBLE_LIST: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readDoubleList", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + break; + case KIND_ROW_LIST: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, elemCodersLocal); + pushInt(mv, pos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readElementList", + "(" + IN_DESC + CODER_DESC + ")Ljava/util/List;", + false); + break; + case KIND_STRING_LONG_MAP: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readStringLongMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + case KIND_STRING_STRING_MAP: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readStringStringMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + case KIND_STRING_INT_MAP: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readStringIntMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + case KIND_STRING_DOUBLE_MAP: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + ROW_WIRE_CODEC, + "readStringDoubleMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + default: + mv.visitVarInsn(Opcodes.ALOAD, codersLocal); + pushInt(mv, pos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + CODER_TYPE, + "decode", + "(" + IN_DESC + ")Ljava/lang/Object;", + false); + break; + } + } + + private enum SourceKind { + ARRAY, + LIST, + ROW + } + + private static final class EncodeFieldsImpl implements Implementation { + private final byte[] fieldKinds; + private final int[] encodingPosToIndex; + private final SourceKind sourceKind; + private final boolean emitNullableHeader; + + EncodeFieldsImpl( + byte[] fieldKinds, + int[] encodingPosToIndex, + SourceKind sourceKind, + boolean emitNullableHeader) { + this.fieldKinds = fieldKinds; + this.encodingPosToIndex = encodingPosToIndex; + this.sourceKind = sourceKind; + this.emitNullableHeader = emitNullableHeader; + } + @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } + private void emitLoadField(MethodVisitor mv, int rowIndex) { + mv.visitVarInsn(Opcodes.ALOAD, 1); + pushInt(mv, rowIndex); + switch (sourceKind) { + case ARRAY: + mv.visitInsn(Opcodes.AALOAD); + break; + case LIST: + mv.visitMethodInsn( + Opcodes.INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;", true); + break; + case ROW: + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, ROW_TYPE, "getValue", "(I)Ljava/lang/Object;", false); + break; + } + } + @Override - public ByteCodeAppender appender(final Target implementationTarget) { - return (methodVisitor, implementationContext, instrumentedMethod) -> { - int numLocals = 1 + instrumentedMethod.getParameters().size(); - StackManipulation stackManipulation = - new StackManipulation.Compound( - // Call the base constructor. - MethodVariableAccess.loadThis(), - Duplication.SINGLE, - MethodInvocation.invoke( - new ForLoadedType(Coder.class) - .getDeclaredMethods() - .filter( - ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0))) - .getOnly()), - Duplication.SINGLE, - // Store the list of Coders as a member variable. - MethodVariableAccess.REFERENCE.loadFrom(1), - FieldAccess.forField( - implementationTarget - .getInstrumentedType() - .getDeclaredFields() - .filter(ElementMatchers.named(CODERS_FIELD_NAME)) - .getOnly()) - .write(), - // Store the list of encoding offsets as a member variable. - MethodVariableAccess.REFERENCE.loadFrom(2), - FieldAccess.forField( - implementationTarget - .getInstrumentedType() - .getDeclaredFields() - .filter(ElementMatchers.named(POSITIONS_FIELD_NAME)) - .getOnly()) - .write(), - MethodReturn.VOID); - StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext); - return new Size(size.getMaximalSize(), numLocals); + public ByteCodeAppender appender(Target target) { + return (mv, context, instrumentedMethod) -> { + int count = fieldKinds.length; + // NoNulls: 0=this, 1=src, 2=out, 3=coders, 4=elemCoders, 5=staticEncoding, 6=fv, 7=pool, + // 8=buf, 9=pos, 10=ex + // Nullable: 0=this, 1=src, 2=out, 3=coders, 4=elemCoders, 5=fv, 6..7=nullMask, 8=pool, + // 9=buf, 10=pos, 11=ex + int fvLocal = emitNullableHeader ? 5 : 6; + int poolLocal = emitNullableHeader ? 8 : 7; + int bufLocal = poolLocal + 1; + int posLocal = bufLocal + 1; + int exLocal = posLocal + 1; + + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + if (emitNullableHeader) { + mv.visitInsn(Opcodes.LCONST_0); + mv.visitVarInsn(Opcodes.LSTORE, 6); + for (int pos = 0; pos < count; pos++) { + Label notNull = new Label(); + emitLoadField(mv, encodingPosToIndex[pos]); + mv.visitJumpInsn(Opcodes.IFNONNULL, notNull); + mv.visitVarInsn(Opcodes.LLOAD, 6); + mv.visitLdcInsn(1L << pos); + mv.visitInsn(Opcodes.LOR); + mv.visitVarInsn(Opcodes.LSTORE, 6); + mv.visitLabel(notNull); + } + } + + // Check out a dedicated scratch buffer from the thread-local pool so re-entrant getters, + // custom Row implementations, or nested coders can never alias this active buffer. + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, bufLocal); + + mv.visitLabel(tryStart); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ISTORE, posLocal); + + if (emitNullableHeader) { + pushInt(mv, count); + mv.visitVarInsn(Opcodes.LLOAD, 6); + emitPackCall(mv, "packHeader", "(IJ" + PACK_SUFFIX, bufLocal, posLocal, 2); + } else { + Label skipHeader = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 5); + mv.visitJumpInsn(Opcodes.IFNE, skipHeader); + pushInt(mv, count); + mv.visitInsn(Opcodes.LCONST_0); + emitPackCall(mv, "packHeader", "(IJ" + PACK_SUFFIX, bufLocal, posLocal, 2); + mv.visitLabel(skipHeader); + } + + for (int pos = 0; pos < count; pos++) { + Label skip = new Label(); + emitLoadField(mv, encodingPosToIndex[pos]); + mv.visitVarInsn(Opcodes.ASTORE, fvLocal); + mv.visitVarInsn(Opcodes.ALOAD, fvLocal); + mv.visitJumpInsn(Opcodes.IFNULL, skip); + emitPackFieldValue(mv, fieldKinds[pos], pos, fvLocal, 2, 3, 4, bufLocal, posLocal); + mv.visitLabel(skip); + } + emitFlush(mv, bufLocal, posLocal, 2); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, exLocal); + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, exLocal); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(8, exLocal + 1); }; } } - private static DynamicType.Builder implementMethods( - Schema schema, DynamicType.Builder builder) { - boolean hasNullableFields = - schema.getFields().stream().map(Field::getType).anyMatch(FieldType::getNullable); - return builder - .defineMethod("getSchema", Schema.class, Visibility.PRIVATE, Ownership.STATIC) - .intercept(FixedValue.reference(schema)) - .defineMethod("hasNullableFields", boolean.class, Visibility.PRIVATE, Ownership.STATIC) - .intercept(FixedValue.reference(hasNullableFields)) - .method(ElementMatchers.named("encode")) - .intercept(new EncodeInstruction()) - .method(ElementMatchers.named("decode")) - .intercept(new DecodeInstruction()); + private static boolean needsScratchForDecode(byte[] fieldKinds) { + for (byte kind : fieldKinds) { + switch (kind) { + case KIND_INT16: + case KIND_FLOAT: + case KIND_DOUBLE: + case KIND_DATETIME: + case KIND_STRING: + case KIND_DECIMAL: + case KIND_STRING_LIST: + case KIND_INT32_LIST: + case KIND_INT64_LIST: + case KIND_DOUBLE_LIST: + case KIND_STRING_LONG_MAP: + case KIND_STRING_STRING_MAP: + case KIND_STRING_INT_MAP: + case KIND_STRING_DOUBLE_MAP: + return true; + default: + break; + } + } + return false; + } + + private static final class DecodeImpl implements Implementation { + private final byte[] fieldKinds; + private final int[] encodingPosToIndex; + private final boolean nullable; + + DecodeImpl(byte[] fieldKinds, int[] encodingPosToIndex, boolean nullable) { + this.fieldKinds = fieldKinds; + this.encodingPosToIndex = encodingPosToIndex; + this.nullable = nullable; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, instrumentedMethod) -> { + int count = fieldKinds.length; + // Nullable: 0=this, 1=in, 2=coders, 3=elemCoders, 4..5=nullMask, 6=buf (owned by caller), + // 7=res + // NoNulls: 0=this, 1=in, 2=coders, 3=elemCoders, 4=res, [5=pool, 6=buf, 7=ex] + // Note: buf holds no live bytes across field boundaries, so nested sub-coder decodes cannot + // observe or corrupt outer decode state (and ScratchPool gives nested decoders distinct + // buffers anyway). + if (nullable) { + int bufLocal = 6; + int resLocal = 7; + pushInt(mv, count); + mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); + mv.visitVarInsn(Opcodes.ASTORE, resLocal); + for (int pos = 0; pos < count; pos++) { + Label skip = new Label(); + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitLdcInsn(1L << pos); + mv.visitInsn(Opcodes.LAND); + mv.visitInsn(Opcodes.LCONST_0); + mv.visitInsn(Opcodes.LCMP); + mv.visitJumpInsn(Opcodes.IFNE, skip); + mv.visitVarInsn(Opcodes.ALOAD, resLocal); + pushInt(mv, encodingPosToIndex[pos]); + emitReadFieldValue(mv, fieldKinds[pos], pos, 1, 2, 3, bufLocal); + mv.visitInsn(Opcodes.AASTORE); + mv.visitLabel(skip); + } + mv.visitVarInsn(Opcodes.ALOAD, resLocal); + mv.visitInsn(Opcodes.ARETURN); + return new ByteCodeAppender.Size(6, resLocal + 1); + } + + boolean needsScratch = needsScratchForDecode(fieldKinds); + int resLocal = 4; + if (!needsScratch) { + pushInt(mv, count); + mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); + mv.visitVarInsn(Opcodes.ASTORE, resLocal); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, resLocal); + pushInt(mv, encodingPosToIndex[pos]); + emitReadFieldValue(mv, fieldKinds[pos], pos, 1, 2, 3, -1); + mv.visitInsn(Opcodes.AASTORE); + } + mv.visitVarInsn(Opcodes.ALOAD, resLocal); + mv.visitInsn(Opcodes.ARETURN); + return new ByteCodeAppender.Size(6, resLocal + 1); + } + + int poolLocal = 5; + int bufLocal = 6; + int exLocal = 7; + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, bufLocal); + + mv.visitLabel(tryStart); + pushInt(mv, count); + mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); + mv.visitVarInsn(Opcodes.ASTORE, resLocal); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, resLocal); + pushInt(mv, encodingPosToIndex[pos]); + emitReadFieldValue(mv, fieldKinds[pos], pos, 1, 2, 3, bufLocal); + mv.visitInsn(Opcodes.AASTORE); + } + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, resLocal); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, exLocal); + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, exLocal); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(6, exLocal + 1); + }; + } } - private static class EncodeInstruction implements Implementation { - static final ForLoadedType LOADED_TYPE = new ForLoadedType(EncodeInstruction.class); + private static final class EncodeChunkImpl implements Implementation { + private final byte[] fieldKinds; + private final int[] encodingPosToIndex; + private final int start; + private final int end; + private final SourceKind sourceKind; + + EncodeChunkImpl( + byte[] fieldKinds, int[] encodingPosToIndex, int start, int end, SourceKind sourceKind) { + this.fieldKinds = fieldKinds; + this.encodingPosToIndex = encodingPosToIndex; + this.start = start; + this.end = end; + this.sourceKind = sourceKind; + } @Override - public ByteCodeAppender appender(Target implementationTarget) { - return (methodVisitor, implementationContext, instrumentedMethod) -> { - StackManipulation manipulation = - new StackManipulation.Compound( - // Array of coders. - MethodVariableAccess.loadThis(), - FieldAccess.forField( - implementationContext - .getInstrumentedType() - .getDeclaredFields() - .filter(ElementMatchers.named(CODERS_FIELD_NAME)) - .getOnly()) - .read(), - MethodVariableAccess.loadThis(), - FieldAccess.forField( - implementationContext - .getInstrumentedType() - .getDeclaredFields() - .filter(ElementMatchers.named(POSITIONS_FIELD_NAME)) - .getOnly()) - .read(), - // Element to encode. (offset 1, as offset 0 is always "this"). - MethodVariableAccess.REFERENCE.loadFrom(1), - // OutputStream. - MethodVariableAccess.REFERENCE.loadFrom(2), - // hasNullableFields - MethodInvocation.invoke( - implementationContext - .getInstrumentedType() - .getDeclaredMethods() - .filter(ElementMatchers.named("hasNullableFields")) - .getOnly()), - // Call EncodeInstruction.encodeDelegate - MethodInvocation.invoke( - LOADED_TYPE - .getDeclaredMethods() - .filter( - ElementMatchers.isStatic().and(ElementMatchers.named("encodeDelegate"))) - .getOnly()), - MethodReturn.VOID); - StackManipulation.Size size = manipulation.apply(methodVisitor, implementationContext); - return new ByteCodeAppender.Size(size.getMaximalSize(), instrumentedMethod.getStackSize()); + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, instrumentedMethod) -> { + // Static method slots: 0=src, 1=buf, 2=pos, 3=out, 4=coders, 5=elemCoders, 6=fv + int fvLocal = 6; + for (int pos = start; pos < end; pos++) { + Label skip = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + pushInt(mv, encodingPosToIndex[pos]); + switch (sourceKind) { + case ARRAY: + mv.visitInsn(Opcodes.AALOAD); + break; + case LIST: + mv.visitMethodInsn( + Opcodes.INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;", true); + break; + case ROW: + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, ROW_TYPE, "getValue", "(I)Ljava/lang/Object;", false); + break; + } + mv.visitVarInsn(Opcodes.ASTORE, fvLocal); + mv.visitVarInsn(Opcodes.ALOAD, fvLocal); + mv.visitJumpInsn(Opcodes.IFNULL, skip); + emitPackFieldValue(mv, fieldKinds[pos], pos, fvLocal, 3, 4, 5, 1, 2); + mv.visitLabel(skip); + } + mv.visitVarInsn(Opcodes.ILOAD, 2); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(8, fvLocal + 1); }; } + } + + private static final class ChunkedEncodeDispatchImpl implements Implementation { + private final int chunkCount; + private final SourceKind sourceKind; + + ChunkedEncodeDispatchImpl(int chunkCount, SourceKind sourceKind) { + this.chunkCount = chunkCount; + this.sourceKind = sourceKind; + } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } - // The encode method of the generated Coder delegates to this method to evaluate all of the - // per-field Coders. - @SuppressWarnings("unchecked") - static void encodeDelegate( + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, instrumentedMethod) -> { + String ownerInternal = target.getInstrumentedType().getInternalName(); + String prefix; + String srcDesc; + switch (sourceKind) { + case ARRAY: + prefix = "encArrC"; + srcDesc = "[Ljava/lang/Object;"; + break; + case LIST: + prefix = "encListC"; + srcDesc = "Ljava/util/List;"; + break; + default: + prefix = "encRowC"; + srcDesc = "L" + ROW_TYPE + ";"; + break; + } + String chunkDesc = + "(" + srcDesc + "[BI" + OUT_DESC + "[" + CODER_DESC + "[" + CODER_DESC + ")I"; + // Instance slots: 0=this, 1=src, 2=out, 3=coders, 4=elemCoders, 5=buf, 6=pos + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, ownerInternal, prefix + c, chunkDesc, false); + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(6, 7); + }; + } + } + + private static final class DecodeChunkImpl implements Implementation { + private final byte[] fieldKinds; + private final int[] encodingPosToIndex; + private final int start; + private final int end; + private final boolean nullable; + + DecodeChunkImpl( + byte[] fieldKinds, int[] encodingPosToIndex, int start, int end, boolean nullable) { + this.fieldKinds = fieldKinds; + this.encodingPosToIndex = encodingPosToIndex; + this.start = start; + this.end = end; + this.nullable = nullable; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, instrumentedMethod) -> { + // Static slots: 0=res, 1=in, 2=coders, 3=elemCoders, 4=buf [, 5=chunkMask] + if (nullable) { + for (int pos = start; pos < end; pos++) { + int bit = pos - start; + Label skip = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 5); + pushInt(mv, 1 << bit); + mv.visitInsn(Opcodes.IAND); + mv.visitJumpInsn(Opcodes.IFNE, skip); + mv.visitVarInsn(Opcodes.ALOAD, 0); + pushInt(mv, encodingPosToIndex[pos]); + emitReadFieldValue(mv, fieldKinds[pos], pos, 1, 2, 3, 4); + mv.visitInsn(Opcodes.AASTORE); + mv.visitLabel(skip); + } + mv.visitInsn(Opcodes.RETURN); + return new ByteCodeAppender.Size(6, 6); + } + + for (int pos = start; pos < end; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + pushInt(mv, encodingPosToIndex[pos]); + emitReadFieldValue(mv, fieldKinds[pos], pos, 1, 2, 3, 4); + mv.visitInsn(Opcodes.AASTORE); + } + mv.visitInsn(Opcodes.RETURN); + return new ByteCodeAppender.Size(6, 5); + }; + } + } + + private static final class ChunkedDecodeDispatchImpl implements Implementation { + private final int fieldCount; + private final int chunkCount; + private final boolean nullable; + + ChunkedDecodeDispatchImpl(int fieldCount, int chunkCount, boolean nullable) { + this.fieldCount = fieldCount; + this.chunkCount = chunkCount; + this.nullable = nullable; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, instrumentedMethod) -> { + String ownerInternal = target.getInstrumentedType().getInternalName(); + String noNullDesc = + "([Ljava/lang/Object;" + IN_DESC + "[" + CODER_DESC + "[" + CODER_DESC + "[B)V"; + if (!nullable) { + // Instance slots: 0=this, 1=in, 2=coders, 3=elemCoders, 4=buf, 5=res + pushInt(mv, fieldCount); + mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); + mv.visitVarInsn(Opcodes.ASTORE, 5); + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ownerInternal, "decNoNullC" + c, noNullDesc, false); + } + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitInsn(Opcodes.ARETURN); + return new ByteCodeAppender.Size(6, 6); + } + + // Instance slots: 0=this, 1=in, 2=coders, 3=elemCoders, 4=nullBytes, 5=nullByteLen, + // 6=buf, 7=res, 8=chunkMask + String nullDesc = + "([Ljava/lang/Object;" + IN_DESC + "[" + CODER_DESC + "[" + CODER_DESC + "[BI)V"; + pushInt(mv, fieldCount); + mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); + mv.visitVarInsn(Opcodes.ASTORE, 7); + for (int c = 0; c < chunkCount; c++) { + Label chunkHasNulls = new Label(); + Label nextChunk = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitVarInsn(Opcodes.ILOAD, 5); + pushInt(mv, c); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ROW_WIRE_CODEC, "extractChunkNullMask32", "([BII)I", false); + mv.visitVarInsn(Opcodes.ISTORE, 8); + mv.visitVarInsn(Opcodes.ILOAD, 8); + mv.visitJumpInsn(Opcodes.IFNE, chunkHasNulls); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, ownerInternal, "decNoNullC" + c, noNullDesc, false); + mv.visitJumpInsn(Opcodes.GOTO, nextChunk); + mv.visitLabel(chunkHasNulls); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitVarInsn(Opcodes.ILOAD, 8); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, ownerInternal, "decNullC" + c, nullDesc, false); + mv.visitLabel(nextChunk); + } + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitInsn(Opcodes.ARETURN); + return new ByteCodeAppender.Size(6, 9); + }; + } + } + + /** + * Concrete, monomorphic {@link Coder} for {@link Row} keeping 100% bit-for-bit compatibility with + * {@code beam:coder:row:v1}. + */ + private static final class GeneratedRowCoder extends CustomCoder { + private final Schema schema; + private final Coder[] coders; + private final @Nullable Coder[] elemCoders; + private final byte[] fieldKinds; + private final int[] encodingPosToIndex; + private final int fieldCount; + private final boolean hasNullableFields; + private final boolean identityPositions; + private final boolean schemaStaticEncoding; + // >= 0 iff !hasNullableFields and every field is a fixed-width primitive (payload size only, + // excluding optional header bytes). + private final long fixedPayloadSize; + private final long defaultHeaderSize; + // Transient: dynamically generated ByteBuddy subclass is not Serializable; readResolve + // re-acquires the cached GeneratedRowCoder (including its fieldCodec) after deserialization. + private transient @Nullable RowFieldCodec fieldCodec; + private final transient boolean chunkedFieldCodec; + private final boolean needsDecodeScratch; + // Encoding positions that may fail isRegisterByteSizeObserverCheap (STRING, containers, ROW, + // OTHER); null when every field is unconditionally O(1) cheap to size. + private final @Nullable int[] cheapCheckPositions; + + GeneratedRowCoder( + Schema schema, Coder[] coders, + @Nullable Coder[] elemCoders, + byte[] fieldKinds, int[] encodingPosToIndex, - Row value, - OutputStream outputStream, - boolean hasNullableFields) - throws IOException { - checkState(value.getFieldCount() == value.getSchema().getFieldCount()); - checkState(encodingPosToIndex.length == value.getFieldCount()); + boolean hasNullableFields, + boolean identityPositions, + long fixedPayloadSize, + @Nullable RowFieldCodec fieldCodec) { + this.schema = schema; + this.coders = coders; + this.elemCoders = elemCoders; + this.fieldKinds = fieldKinds; + this.encodingPosToIndex = encodingPosToIndex; + this.fieldCount = coders.length; + this.hasNullableFields = hasNullableFields; + this.identityPositions = identityPositions; + this.schemaStaticEncoding = schema.isStaticEncoding(); + this.fixedPayloadSize = fixedPayloadSize; + // Non-static non-null header: VarInt(fieldCount) + 1 byte (0x00 = empty null bitmap). + this.defaultHeaderSize = VarInt.getLength(fieldCount) + 1L; + this.fieldCodec = fieldCodec; + this.chunkedFieldCodec = fieldCodec != null && this.fieldCount > MAX_UNROLLED_FIELDS; + this.needsDecodeScratch = needsScratchForDecode(fieldKinds); + this.cheapCheckPositions = computeCheapCheckPositions(fieldKinds); + } - boolean staticEncoding = - value.getSchema().getOptions().getValueOrDefault(SCHEMA_OPTION_STATIC_ENCODING, false); + private static @Nullable int[] computeCheapCheckPositions(byte[] fieldKinds) { + int n = 0; + for (byte kind : fieldKinds) { + if (!isAlwaysCheapKind(kind)) { + n++; + } + } + if (n == 0) { + return null; + } + int[] positions = new int[n]; + int out = 0; + for (int pos = 0; pos < fieldKinds.length; pos++) { + if (!isAlwaysCheapKind(fieldKinds[pos])) { + positions[out++] = pos; + } + } + return positions; + } - // Encode the field count. This allows us to handle compatible schema changes. - if (!staticEncoding) { - VAR_INT_CODER.encode(value.getFieldCount(), outputStream); + private static boolean isAlwaysCheapKind(byte kind) { + switch (kind) { + case KIND_BYTE: + case KIND_INT16: + case KIND_INT32: + case KIND_INT64: + case KIND_FLOAT: + case KIND_DOUBLE: + case KIND_BOOLEAN: + case KIND_DATETIME: + case KIND_BYTES: + case KIND_DECIMAL: + case KIND_DATE: + case KIND_TIME: + case KIND_LOCAL_DATETIME: + case KIND_UUID: + case KIND_MICROS_INSTANT: + case KIND_NANOS_INSTANT: + case KIND_NANOS_DURATION: + return true; + default: + return false; } + } - if (hasNullableFields) { - // If the row has null fields, extract the values out once so that both scanNullFields and - // the encoding can share it and avoid having to extract them twice. + private Object readResolve() { + return schema.getUUID() != null ? RowCoderGenerator.generate(schema) : this; + } - Object[] fieldValues = new Object[value.getFieldCount()]; - for (int idx = 0; idx < fieldValues.length; ++idx) { - fieldValues[idx] = value.getValue(idx); - } + @Override + public void encode(Row value, OutputStream outStream) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null Row"); + } + int count = fieldCount; + checkState(value.getFieldCount() == value.getSchema().getFieldCount()); + checkState(count == value.getFieldCount()); - // Encode a bitmap for the null fields to save having to encode a bunch of nulls. - if (!staticEncoding) { - NULL_LIST_CODER.encode(scanNullFields(fieldValues, encodingPosToIndex), outputStream); + boolean staticEncoding = value.getSchema().isStaticEncoding(); + if (!hasNullableFields) { + encodeNonNullFields(value, outStream, staticEncoding); + return; + } + + if (staticEncoding) { + // Static encoding emits neither field count nor null bitmap, so encode in a single pass. + encodeNonNullFields(value, outStream, true); + return; + } + + RowFieldCodec codec = fieldCodec; + boolean singleMethod = codec != null && !chunkedFieldCodec; + if (value instanceof RowWithStorage) { + RowWithStorage storage = (RowWithStorage) value; + Object[] arr = storage.getRawArray(); + if (arr != null) { + if (singleMethod) { + codec.encodeArrayNullable(arr, outStream, coders, elemCoders); + } else { + encodeNullableArray(arr, outStream); + } + return; } - for (int encodingPos = 0; encodingPos < fieldValues.length; ++encodingPos) { - @Nullable Object fieldValue = fieldValues[encodingPosToIndex[encodingPos]]; - if (fieldValue != null) { - coders[encodingPos].encode(fieldValue, outputStream); + List list = storage.getValues(); + if (list instanceof RandomAccess) { + if (singleMethod) { + codec.encodeListNullable(list, outStream, coders, elemCoders); + } else { + encodeNullableList(list, outStream); + } + } else { + Object[] extracted = list.toArray(); + if (singleMethod) { + codec.encodeArrayNullable(extracted, outStream, coders, elemCoders); + } else { + encodeNullableArray(extracted, outStream); } } + return; + } + + Object[] extracted = new Object[count]; + for (int i = 0; i < count; i++) { + extracted[i] = value.getValue(i); + } + if (singleMethod) { + codec.encodeArrayNullable(extracted, outStream, coders, elemCoders); } else { - // Otherwise, we know all fields are non-null, so the null list is always empty. + encodeNullableArray(extracted, outStream); + } + } + private void encodeNonNullFields(Row value, OutputStream out, boolean staticEncoding) + throws IOException { + int count = fieldCount; + if (count == 0) { if (!staticEncoding) { - NULL_LIST_CODER.encode(EMPTY_BIT_SET, outputStream); + RowWireCodec.writeHeader(0, 0L, out); + } + return; + } + RowFieldCodec codec = fieldCodec; + boolean singleMethod = codec != null && !chunkedFieldCodec; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + if (value instanceof RowWithStorage) { + RowWithStorage storage = (RowWithStorage) value; + Object[] arr = storage.getRawArray(); + if (arr != null) { + if (singleMethod) { + codec.encodeArrayNoNulls(arr, out, localCoders, localElemCoders, staticEncoding); + return; + } + encodeNonNullArrayWide(arr, out, staticEncoding); + return; + } + List list = storage.getValues(); + if (list instanceof RandomAccess) { + if (singleMethod) { + codec.encodeListNoNulls(list, out, localCoders, localElemCoders, staticEncoding); + return; + } + encodeNonNullListWide(list, out, staticEncoding); + return; } - for (int encodingPos = 0; encodingPos < value.getFieldCount(); ++encodingPos) { - @Nullable Object fieldValue = value.getValue(encodingPosToIndex[encodingPos]); - if (fieldValue != null) { - coders[encodingPos].encode(fieldValue, outputStream); + Object[] extracted = list.toArray(); + if (singleMethod) { + codec.encodeArrayNoNulls(extracted, out, localCoders, localElemCoders, staticEncoding); + return; + } + encodeNonNullArrayWide(extracted, out, staticEncoding); + return; + } + + if (singleMethod) { + codec.encodeRowNoNulls(value, out, localCoders, localElemCoders, staticEncoding); + return; + } + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + int bufPos = staticEncoding ? 0 : RowWireCodec.packHeader(count, 0L, buf, 0, out); + if (codec != null && codec.supportsRowBody()) { + bufPos = codec.encodeRowBody(value, out, localCoders, localElemCoders, buf, bufPos); + } else { + byte[] kinds = fieldKinds; + int[] map = encodingPosToIndex; + for (int pos = 0; pos < count; pos++) { + Object fv = value.getValue(identityPositions ? pos : map[pos]); + if (fv != null) { + bufPos = + packField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + fv, + buf, + bufPos, + out); + } } } + RowWireCodec.flush(buf, bufPos, out); + } finally { + pool.release(buf); } } - // Figure out which fields of the Row are null, and returns a BitSet. This allows us to save - // on encoding each null field separately. - private static BitSet scanNullFields(Object[] fieldValues, int[] encodingPosToIndex) { - Preconditions.checkState(fieldValues.length == encodingPosToIndex.length); - BitSet nullFields = new BitSet(fieldValues.length); - for (int encodingPos = 0; encodingPos < encodingPosToIndex.length; ++encodingPos) { - int fieldIndex = encodingPosToIndex[encodingPos]; - if (fieldValues[fieldIndex] == null) { - nullFields.set(encodingPos); + private void encodeNonNullArrayWide(Object[] arr, OutputStream out, boolean staticEncoding) + throws IOException { + int count = fieldCount; + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + int bufPos = staticEncoding ? 0 : RowWireCodec.packHeader(count, 0L, buf, 0, out); + RowFieldCodec codec = fieldCodec; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + if (codec != null && chunkedFieldCodec) { + bufPos = codec.encodeArrayBody(arr, out, localCoders, localElemCoders, buf, bufPos); + } else { + byte[] kinds = fieldKinds; + int[] map = encodingPosToIndex; + for (int pos = 0; pos < count; pos++) { + Object fv = arr[identityPositions ? pos : map[pos]]; + if (fv != null) { + bufPos = + packField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + fv, + buf, + bufPos, + out); + } + } } + RowWireCodec.flush(buf, bufPos, out); + } finally { + pool.release(buf); } - return nullFields; } - } - private static class DecodeInstruction implements Implementation { - static final ForLoadedType LOADED_TYPE = new ForLoadedType(DecodeInstruction.class); + private void encodeNonNullListWide(List list, OutputStream out, boolean staticEncoding) + throws IOException { + int count = fieldCount; + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + int bufPos = staticEncoding ? 0 : RowWireCodec.packHeader(count, 0L, buf, 0, out); + RowFieldCodec codec = fieldCodec; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + if (codec != null && chunkedFieldCodec) { + bufPos = codec.encodeListBody(list, out, localCoders, localElemCoders, buf, bufPos); + } else { + byte[] kinds = fieldKinds; + int[] map = encodingPosToIndex; + for (int pos = 0; pos < count; pos++) { + Object fv = list.get(identityPositions ? pos : map[pos]); + if (fv != null) { + bufPos = + packField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + fv, + buf, + bufPos, + out); + } + } + } + RowWireCodec.flush(buf, bufPos, out); + } finally { + pool.release(buf); + } + } - @Override - public ByteCodeAppender appender(Target implementationTarget) { - return (methodVisitor, implementationContext, instrumentedMethod) -> { - StackManipulation manipulation = - new StackManipulation.Compound( - // Schema. Used in generation of DecodeInstruction. - MethodInvocation.invoke( - implementationContext - .getInstrumentedType() - .getDeclaredMethods() - .filter(ElementMatchers.named("getSchema")) - .getOnly()), - // Array of coders. - MethodVariableAccess.loadThis(), - FieldAccess.forField( - implementationContext - .getInstrumentedType() - .getDeclaredFields() - .filter(ElementMatchers.named(CODERS_FIELD_NAME)) - .getOnly()) - .read(), - MethodVariableAccess.loadThis(), - FieldAccess.forField( - implementationContext - .getInstrumentedType() - .getDeclaredFields() - .filter(ElementMatchers.named(POSITIONS_FIELD_NAME)) - .getOnly()) - .read(), - // read the InputStream. (offset 1, as offset 0 is always "this"). - MethodVariableAccess.REFERENCE.loadFrom(1), - MethodInvocation.invoke( - LOADED_TYPE - .getDeclaredMethods() - .filter( - ElementMatchers.isStatic().and(ElementMatchers.named("decodeDelegate"))) - .getOnly()), - MethodReturn.REFERENCE); - StackManipulation.Size size = manipulation.apply(methodVisitor, implementationContext); - return new ByteCodeAppender.Size(size.getMaximalSize(), instrumentedMethod.getStackSize()); - }; + private void encodeNullableArray(Object[] arr, OutputStream out) throws IOException { + int count = fieldCount; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + int bufPos = encodeNullableHeader(arr, null, count, buf, out); + RowFieldCodec codec = fieldCodec; + if (codec != null && chunkedFieldCodec) { + bufPos = codec.encodeArrayBody(arr, out, localCoders, localElemCoders, buf, bufPos); + } else { + byte[] kinds = fieldKinds; + int[] map = encodingPosToIndex; + for (int pos = 0; pos < count; pos++) { + Object v = arr[identityPositions ? pos : map[pos]]; + if (v != null) { + bufPos = + packField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + v, + buf, + bufPos, + out); + } + } + } + RowWireCodec.flush(buf, bufPos, out); + } finally { + pool.release(buf); + } + } + + private void encodeNullableList(List list, OutputStream out) throws IOException { + int count = fieldCount; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + int bufPos = encodeNullableHeader(null, list, count, buf, out); + RowFieldCodec codec = fieldCodec; + if (codec != null && chunkedFieldCodec) { + bufPos = codec.encodeListBody(list, out, localCoders, localElemCoders, buf, bufPos); + } else { + byte[] kinds = fieldKinds; + int[] map = encodingPosToIndex; + for (int pos = 0; pos < count; pos++) { + Object v = list.get(identityPositions ? pos : map[pos]); + if (v != null) { + bufPos = + packField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + v, + buf, + bufPos, + out); + } + } + } + RowWireCodec.flush(buf, bufPos, out); + } finally { + pool.release(buf); + } + } + + private int encodeNullableHeader( + @Nullable Object[] arr, + @Nullable List list, + int count, + byte[] buf, + OutputStream out) + throws IOException { + int[] map = encodingPosToIndex; + if (count <= 64) { + long nullMask = 0L; + for (int pos = 0; pos < count; pos++) { + int idx = identityPositions ? pos : map[pos]; + Object v = arr != null ? arr[idx] : list.get(idx); + if (v == null) { + nullMask |= (1L << pos); + } + } + return RowWireCodec.packHeader(count, nullMask, buf, 0, out); + } + if (arr != null) { + return RowWireCodec.packWideNullHeaderFromArray( + arr, map, identityPositions, count, buf, out); + } + return RowWireCodec.packWideNullHeaderFromList(list, map, identityPositions, count, buf, out); } @Override - public InstrumentedType prepare(InstrumentedType instrumentedType) { - return instrumentedType; + public Row decode(InputStream inStream) throws IOException { + if (schemaStaticEncoding) { + int localFieldCount = fieldCount; + if (localFieldCount == 0) { + return Row.attachValues(schema, EMPTY_VALUES); + } + RowFieldCodec codec = fieldCodec; + if (codec != null) { + if (!chunkedFieldCodec) { + return Row.attachValues(schema, codec.decodeNoNulls(inStream, coders, elemCoders)); + } + if (!needsDecodeScratch) { + return Row.attachValues( + schema, codec.decodeNoNullsWide(inStream, coders, elemCoders, null)); + } + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + return Row.attachValues( + schema, codec.decodeNoNullsWide(inStream, coders, elemCoders, buf)); + } finally { + pool.release(buf); + } + } + Object[] fieldValues = new Object[localFieldCount]; + decodeNoNullLoop(fieldValues, localFieldCount, inStream); + return Row.attachValues(schema, fieldValues); + } + + int streamFieldCount = RowWireCodec.readVarInt(inStream); + int nullByteLen = RowWireCodec.readVarInt(inStream); + return decodeAfterNullByteLen(streamFieldCount, nullByteLen, inStream); } - // The decode method of the generated Coder delegates to this method to evaluate all of the - // per-field Coders. - static Row decodeDelegate( - Schema schema, Coder[] coders, int[] encodingPosToIndex, InputStream inputStream) + Row decodeAfterNullByteLen(int streamFieldCount, int nullByteLen, InputStream inStream) throws IOException { - int fieldCount; - BitSet nullFields; - if (schema.getOptions().getValueOrDefault(SCHEMA_OPTION_STATIC_ENCODING, false)) { - fieldCount = schema.getFieldCount(); - nullFields = new BitSet(); - } else { - fieldCount = VAR_INT_CODER.decode(inputStream); - nullFields = NULL_LIST_CODER.decode(inputStream); - } - Object[] fieldValues = new Object[coders.length]; - for (int encodingPos = 0; encodingPos < fieldCount; ++encodingPos) { - // In the case of a schema change going backwards, fieldCount might be > coders.length, - // in which case we drop the extra fields. - if (encodingPos < coders.length) { - int rowIndex = encodingPosToIndex[encodingPos]; - if (nullFields.get(encodingPos)) { - fieldValues[rowIndex] = null; - } else { - Object fieldValue = coders[encodingPos].decode(inputStream); - fieldValues[rowIndex] = fieldValue; + if (nullByteLen < 0) { + throw new CoderException("Invalid null bitset length: " + nullByteLen); + } + int localFieldCount = fieldCount; + if (localFieldCount == 0) { + if (nullByteLen > 0) { + RowWireCodec.skipExact(inStream, nullByteLen); + } + return Row.attachValues(schema, EMPTY_VALUES); + } + + RowFieldCodec codec = fieldCodec; + boolean hasChunked = codec != null && chunkedFieldCodec; + if (nullByteLen == 0) { + if (codec != null && streamFieldCount >= localFieldCount) { + if (!hasChunked) { + return Row.attachValues(schema, codec.decodeNoNulls(inStream, coders, elemCoders)); + } + if (!needsDecodeScratch) { + return Row.attachValues( + schema, codec.decodeNoNullsWide(inStream, coders, elemCoders, null)); + } + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + return Row.attachValues( + schema, codec.decodeNoNullsWide(inStream, coders, elemCoders, buf)); + } finally { + pool.release(buf); + } + } + Object[] fieldValues = new Object[localFieldCount]; + int decodeCount = Math.min(streamFieldCount, localFieldCount); + decodeNoNullLoop(fieldValues, decodeCount, inStream); + return Row.attachValues(schema, fieldValues); + } + + if (nullByteLen <= 8 && !hasChunked) { + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + long nullMask = RowWireCodec.readNullMask(inStream, nullByteLen, buf); + if (codec != null && streamFieldCount >= localFieldCount) { + return Row.attachValues( + schema, codec.decodeNullable(inStream, coders, elemCoders, nullMask, buf)); + } + Object[] fieldValues = new Object[localFieldCount]; + int decodeCount = Math.min(streamFieldCount, localFieldCount); + byte[] kinds = fieldKinds; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + int[] map = encodingPosToIndex; + for (int pos = 0; pos < decodeCount; pos++) { + if (pos >= 64 || (nullMask & (1L << pos)) == 0L) { + fieldValues[identityPositions ? pos : map[pos]] = + decodeField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + inStream, + buf); + } + } + return Row.attachValues(schema, fieldValues); + } finally { + pool.release(buf); + } + } + + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] nullScratch = pool.acquire(); + @Nullable byte[] buf = null; + try { + if (needsDecodeScratch) { + buf = pool.acquire(); + } + byte[] nullBytes = RowWireCodec.readNullBytes(inStream, nullByteLen, nullScratch); + if (hasChunked + && codec.supportsNullableWideDecode() + && streamFieldCount >= localFieldCount) { + return Row.attachValues( + schema, + codec.decodeNullableWide(inStream, coders, elemCoders, nullBytes, nullByteLen, buf)); + } + Object[] fieldValues = new Object[localFieldCount]; + int decodeCount = Math.min(streamFieldCount, localFieldCount); + byte[] kinds = fieldKinds; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + int[] map = encodingPosToIndex; + for (int pos = 0; pos < decodeCount; pos++) { + if (!RowWireCodec.isNullBitSet(nullBytes, nullByteLen, pos)) { + fieldValues[identityPositions ? pos : map[pos]] = + decodeField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + inStream, + buf); } } + return Row.attachValues(schema, fieldValues); + } finally { + if (buf != null) { + pool.release(buf); + } + pool.release(nullScratch); + } + } + + private void decodeNoNullLoop(Object[] fieldValues, int decodeCount, InputStream inStream) + throws IOException { + byte[] kinds = fieldKinds; + Coder[] localCoders = coders; + Coder[] localElemCoders = elemCoders; + int[] map = encodingPosToIndex; + if (!needsDecodeScratch) { + for (int pos = 0; pos < decodeCount; pos++) { + fieldValues[identityPositions ? pos : map[pos]] = + decodeField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + inStream, + null); + } + return; + } + RowWireCodec.ScratchPool pool = RowWireCodec.scratchPool(); + byte[] buf = pool.acquire(); + try { + for (int pos = 0; pos < decodeCount; pos++) { + fieldValues[identityPositions ? pos : map[pos]] = + decodeField( + kinds[pos], + localCoders[pos], + localElemCoders != null ? localElemCoders[pos] : null, + inStream, + buf); + } + } finally { + pool.release(buf); + } + } + + @Override + public boolean isRegisterByteSizeObserverCheap(Row value) { + if (value == null) { + return false; + } + @Nullable int[] checkPositions = cheapCheckPositions; + if (checkPositions == null) { + return true; } - // If the schema was evolved to contain more fields, we fill them in with nulls. - for (int encodingPos = fieldCount; encodingPos < coders.length; encodingPos++) { - int rowIndex = encodingPosToIndex[encodingPos]; - fieldValues[rowIndex] = null; + byte[] kinds = fieldKinds; + Coder[] localCoders = coders; + int[] map = encodingPosToIndex; + for (int pos : checkPositions) { + Object fv = value.getValue(identityPositions ? pos : map[pos]); + if (fv == null) { + continue; + } + if (kinds[pos] == KIND_STRING) { + if (((String) fv).length() > 1024) { + return false; + } + } else if (!localCoders[pos].isRegisterByteSizeObserverCheap(fv)) { + return false; + } + } + return true; + } + + @Override + @SuppressWarnings("unchecked") + public void registerByteSizeObserver(Row value, ElementByteSizeObserver observer) + throws Exception { + if (value == null) { + throw new CoderException("cannot observe a null Row"); + } + boolean staticEncoding = value.getSchema().isStaticEncoding(); + if (fixedPayloadSize >= 0L) { + observer.update(staticEncoding ? fixedPayloadSize : (defaultHeaderSize + fixedPayloadSize)); + return; + } + + int count = fieldCount; + checkState(value.getFieldCount() == value.getSchema().getFieldCount()); + checkState(count == value.getFieldCount()); + + long directBytes = 0L; + int highestNullPos = -1; + byte[] kinds = fieldKinds; + Coder[] localCoders = coders; + int[] map = encodingPosToIndex; + + if (!staticEncoding) { + directBytes += VarInt.getLength(count); + } + + Object[] rawArr = null; + List rawList = null; + if (value instanceof RowWithStorage) { + RowWithStorage storage = (RowWithStorage) value; + rawArr = storage.getRawArray(); + if (rawArr == null) { + List vals = storage.getValues(); + if (vals instanceof RandomAccess) { + rawList = vals; + } + } + } + for (int pos = 0; pos < count; pos++) { + int idx = identityPositions ? pos : map[pos]; + Object fv = + rawArr != null + ? rawArr[idx] + : (rawList != null ? rawList.get(idx) : value.getValue(idx)); + if (fv == null) { + if (hasNullableFields) { + highestNullPos = pos; + } + continue; + } + switch (kinds[pos]) { + case KIND_BYTE: + case KIND_BOOLEAN: + directBytes += 1L; + break; + case KIND_INT16: + directBytes += 2L; + break; + case KIND_FLOAT: + directBytes += 4L; + break; + case KIND_DOUBLE: + case KIND_DATETIME: + directBytes += 8L; + break; + case KIND_INT32: + directBytes += VarInt.getLength(((Integer) fv).intValue()); + break; + case KIND_INT64: + directBytes += VarInt.getLength(((Long) fv).longValue()); + break; + case KIND_BYTES: + directBytes += RowWireCodec.sizeOfBytes((byte[]) fv); + break; + case KIND_STRING: + directBytes += RowWireCodec.sizeOfString((String) fv); + break; + case KIND_DECIMAL: + directBytes += RowWireCodec.sizeOfDecimal((BigDecimal) fv); + break; + case KIND_DATE: + directBytes += RowWireCodec.sizeOfLocalDate((LocalDate) fv); + break; + case KIND_TIME: + directBytes += RowWireCodec.sizeOfLocalTime((LocalTime) fv); + break; + case KIND_LOCAL_DATETIME: + directBytes += RowWireCodec.sizeOfLocalDateTime((LocalDateTime) fv); + break; + case KIND_UUID: + directBytes += RowWireCodec.sizeOfUuid((UUID) fv); + break; + case KIND_MICROS_INSTANT: + directBytes += RowWireCodec.sizeOfMicrosInstant((java.time.Instant) fv); + break; + case KIND_NANOS_INSTANT: + directBytes += RowWireCodec.sizeOfNanosInstant((java.time.Instant) fv); + break; + case KIND_NANOS_DURATION: + directBytes += RowWireCodec.sizeOfNanosDuration((Duration) fv); + break; + case KIND_STRING_LIST: + if (fv instanceof Collection && !(fv instanceof ElementByteSizeObservableIterable)) { + directBytes += RowWireCodec.sizeOfStringCollection((Collection) fv); + } else { + localCoders[pos].registerByteSizeObserver(fv, observer); + } + break; + case KIND_INT32_LIST: + if (fv instanceof Collection && !(fv instanceof ElementByteSizeObservableIterable)) { + directBytes += RowWireCodec.sizeOfInt32Collection((Collection) fv); + } else { + localCoders[pos].registerByteSizeObserver(fv, observer); + } + break; + case KIND_INT64_LIST: + if (fv instanceof Collection && !(fv instanceof ElementByteSizeObservableIterable)) { + directBytes += RowWireCodec.sizeOfInt64Collection((Collection) fv); + } else { + localCoders[pos].registerByteSizeObserver(fv, observer); + } + break; + case KIND_DOUBLE_LIST: + if (fv instanceof Collection && !(fv instanceof ElementByteSizeObservableIterable)) { + directBytes += RowWireCodec.sizeOfDoubleCollection((Collection) fv); + } else { + localCoders[pos].registerByteSizeObserver(fv, observer); + } + break; + case KIND_STRING_LONG_MAP: + directBytes += RowWireCodec.sizeOfStringLongMap((Map) fv); + break; + case KIND_STRING_STRING_MAP: + directBytes += RowWireCodec.sizeOfStringStringMap((Map) fv); + break; + case KIND_STRING_INT_MAP: + directBytes += RowWireCodec.sizeOfStringIntMap((Map) fv); + break; + case KIND_STRING_DOUBLE_MAP: + directBytes += RowWireCodec.sizeOfStringDoubleMap((Map) fv); + break; + default: + localCoders[pos].registerByteSizeObserver(fv, observer); + break; + } + } + + if (!staticEncoding) { + directBytes += RowWireCodec.sizeOfNullMask(highestNullPos); + } + if (directBytes > 0L || count == 0) { + observer.update(directBytes); + } + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + Coder.verifyDeterministic( + this, "All fields must have deterministic encoding", Arrays.asList(coders)); + } + + @Override + public boolean consistentWithEquals() { + return true; + } + + @SuppressWarnings("unchecked") + private static int packField( + byte kind, + Coder coder, + @Nullable Coder elemCoder, + Object fieldValue, + byte[] buf, + int pos, + OutputStream out) + throws IOException { + switch (kind) { + case KIND_BYTE: + return RowWireCodec.packByte(((Byte) fieldValue).byteValue(), buf, pos, out); + case KIND_INT16: + return RowWireCodec.packInt16(((Short) fieldValue).shortValue(), buf, pos, out); + case KIND_INT32: + return RowWireCodec.packVarInt(((Integer) fieldValue).intValue(), buf, pos, out); + case KIND_INT64: + return RowWireCodec.packVarLong(((Long) fieldValue).longValue(), buf, pos, out); + case KIND_FLOAT: + return RowWireCodec.packFloat(((Float) fieldValue).floatValue(), buf, pos, out); + case KIND_DOUBLE: + return RowWireCodec.packDouble(((Double) fieldValue).doubleValue(), buf, pos, out); + case KIND_BOOLEAN: + return RowWireCodec.packBoolean(((Boolean) fieldValue).booleanValue(), buf, pos, out); + case KIND_DATETIME: + return RowWireCodec.packDateTime((ReadableInstant) fieldValue, buf, pos, out); + case KIND_STRING: + return RowWireCodec.packString((String) fieldValue, buf, pos, out); + case KIND_BYTES: + return RowWireCodec.packBytes((byte[]) fieldValue, buf, pos, out); + case KIND_DECIMAL: + return RowWireCodec.packDecimal((BigDecimal) fieldValue, buf, pos, out); + case KIND_DATE: + return RowWireCodec.packLocalDate((LocalDate) fieldValue, buf, pos, out); + case KIND_TIME: + return RowWireCodec.packLocalTime((LocalTime) fieldValue, buf, pos, out); + case KIND_LOCAL_DATETIME: + return RowWireCodec.packLocalDateTime((LocalDateTime) fieldValue, buf, pos, out); + case KIND_UUID: + return RowWireCodec.packUuid((UUID) fieldValue, buf, pos, out); + case KIND_MICROS_INSTANT: + return RowWireCodec.packMicrosInstant((java.time.Instant) fieldValue, buf, pos, out); + case KIND_NANOS_INSTANT: + return RowWireCodec.packNanosInstant((java.time.Instant) fieldValue, buf, pos, out); + case KIND_NANOS_DURATION: + return RowWireCodec.packNanosDuration((Duration) fieldValue, buf, pos, out); + case KIND_STRING_LIST: + return RowWireCodec.packStringIterable( + (Iterable) fieldValue, buf, pos, out, coder); + case KIND_INT32_LIST: + return RowWireCodec.packInt32Iterable( + (Iterable) fieldValue, buf, pos, out, coder); + case KIND_INT64_LIST: + return RowWireCodec.packInt64Iterable((Iterable) fieldValue, buf, pos, out, coder); + case KIND_DOUBLE_LIST: + return RowWireCodec.packDoubleIterable( + (Iterable) fieldValue, buf, pos, out, coder); + case KIND_ROW_LIST: + RowWireCodec.flush(buf, pos, out); + RowWireCodec.writeElementIterable((Iterable) fieldValue, elemCoder, out, coder); + return 0; + case KIND_STRING_LONG_MAP: + return RowWireCodec.packStringLongMap((Map) fieldValue, buf, pos, out); + case KIND_STRING_STRING_MAP: + return RowWireCodec.packStringStringMap((Map) fieldValue, buf, pos, out); + case KIND_STRING_INT_MAP: + return RowWireCodec.packStringIntMap((Map) fieldValue, buf, pos, out); + case KIND_STRING_DOUBLE_MAP: + return RowWireCodec.packStringDoubleMap((Map) fieldValue, buf, pos, out); + case KIND_ROW: + default: + RowWireCodec.flush(buf, pos, out); + coder.encode(fieldValue, out); + return 0; + } + } + + private static Object decodeField( + byte kind, Coder coder, @Nullable Coder elemCoder, InputStream in, byte[] buf) + throws IOException { + switch (kind) { + case KIND_BYTE: + return RowWireCodec.readByte(in); + case KIND_INT16: + return RowWireCodec.readInt16(in, buf); + case KIND_INT32: + return RowWireCodec.readVarInt(in); + case KIND_INT64: + return RowWireCodec.readVarLong(in); + case KIND_FLOAT: + return RowWireCodec.readFloat(in, buf); + case KIND_DOUBLE: + return RowWireCodec.readDouble(in, buf); + case KIND_BOOLEAN: + return RowWireCodec.readBoolean(in) ? Boolean.TRUE : Boolean.FALSE; + case KIND_DATETIME: + return RowWireCodec.readDateTime(in, buf); + case KIND_STRING: + return RowWireCodec.readString(in, buf); + case KIND_BYTES: + return RowWireCodec.readBytes(in); + case KIND_DECIMAL: + return RowWireCodec.readDecimal(in, buf); + case KIND_DATE: + return RowWireCodec.readLocalDate(in); + case KIND_TIME: + return RowWireCodec.readLocalTime(in); + case KIND_LOCAL_DATETIME: + return RowWireCodec.readLocalDateTime(in); + case KIND_UUID: + return RowWireCodec.readUuid(in); + case KIND_MICROS_INSTANT: + return RowWireCodec.readMicrosInstant(in); + case KIND_NANOS_INSTANT: + return RowWireCodec.readNanosInstant(in); + case KIND_NANOS_DURATION: + return RowWireCodec.readNanosDuration(in); + case KIND_STRING_LIST: + return RowWireCodec.readStringList(in, buf); + case KIND_INT32_LIST: + return RowWireCodec.readInt32List(in, buf); + case KIND_INT64_LIST: + return RowWireCodec.readInt64List(in, buf); + case KIND_DOUBLE_LIST: + return RowWireCodec.readDoubleList(in, buf); + case KIND_ROW_LIST: + return RowWireCodec.readElementList(in, elemCoder); + case KIND_STRING_LONG_MAP: + return RowWireCodec.readStringLongMap(in, buf); + case KIND_STRING_STRING_MAP: + return RowWireCodec.readStringStringMap(in, buf); + case KIND_STRING_INT_MAP: + return RowWireCodec.readStringIntMap(in, buf); + case KIND_STRING_DOUBLE_MAP: + return RowWireCodec.readStringDoubleMap(in, buf); + case KIND_ROW: + default: + return coder.decode(in); } - // We call attachValues instead of setValues. setValues validates every element in the list - // is of the proper type, potentially converts to the internal type Row stores, and copies - // all values. Since we assume that decode is always being called on a previously-encoded - // Row, the values should already be validated and of the correct type. So, we can save - // some processing by simply transferring ownership of the list to the Row. - return Row.withSchema(schema).attachValues(fieldValues); } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowWireCodec.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowWireCodec.java new file mode 100644 index 000000000000..aea47ff217d7 --- /dev/null +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/RowWireCodec.java @@ -0,0 +1,2267 @@ +/* + * 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.beam.sdk.coders; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.RandomAccess; +import java.util.UUID; +import org.apache.beam.sdk.annotations.Internal; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.util.VarInt; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Utf8; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Instant; +import org.joda.time.ReadableInstant; + +/** + * Leaf wire-format encoding, decoding, and byte-size helpers matching {@code beam:coder:row:v1} + * bit-for-bit. + * + *

Provides buffered {@code pack*} writers and {@code read*(in, buf)} readers that accept a + * caller-checked-out per-thread scratch buffer ({@link ScratchPool}) so a full row is packed into a + * single {@link OutputStream#write(byte[], int, int)} flush with one {@link ThreadLocal} lookup per + * row. Checkout/release ownership prevents silent buffer clobbering across re-entrant user getters, + * custom streams, lazy collections, or nested {@link Coder}s; callers must still call {@link + * #flush(byte[], int, OutputStream)} before invoking any nested {@link Coder} so bytes arrive in + * wire order. + */ +@Internal +public final class RowWireCodec { + private static final int SCRATCH_SIZE = 512; + // Every fixed-width / varint / logical-type / header write emits at most 24 bytes. + private static final int FLUSH_LIMIT = SCRATCH_SIZE - 32; + // Two VarInt headers (fieldCount + nullByteLen) take at most 10 bytes. + private static final int MAX_HEADER_VARINT_BYTES = 10; + private static final int MAX_ASCII_STRING_FAST = 254; + private static final int MAX_INLINE_BYTES_FAST = 64; + private static final byte[] EMPTY_BYTES = new byte[0]; + + private static final VarHandle SHORT_BE = + MethodHandles.byteArrayViewVarHandle(short[].class, ByteOrder.BIG_ENDIAN); + private static final VarHandle INT_BE = + MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.BIG_ENDIAN); + private static final VarHandle INT_LE = + MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN); + private static final VarHandle LONG_BE = + MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.BIG_ENDIAN); + + private static final ThreadLocal<@Nullable ScratchPool> SCRATCH_POOL = + ThreadLocal.withInitial(ScratchPool::new); + private static final ThreadLocal<@Nullable RefScratchPool> REF_SCRATCH_POOL = + ThreadLocal.withInitial(RefScratchPool::new); + + private static final int[] TIMESTAMP_SCALING_FACTORS = { + 1_000_000_000, 100_000_000, 10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10, 1 + }; + private static final int[] TIMESTAMP_MAX_SUBSECONDS = { + 0, 9, 99, 999, 9_999, 99_999, 999_999, 9_999_999, 99_999_999, 999_999_999 + }; + + /** + * Per-thread re-entrancy-safe pool of 512-byte scratch buffers. + * + *

Each {@link #acquire()} removes a buffer from the thread-local stack (allocating a fresh + * buffer only if re-entrancy exceeds {@link #MAX_DEPTH}), guaranteeing nested or re-entrant + * encoders/decoders on the same thread never alias an active caller's buffer. + */ + @Internal + public static final class ScratchPool { + private static final int MAX_DEPTH = 8; + private final byte[] @Nullable [] stack = new byte[MAX_DEPTH][]; + private int depth; + + ScratchPool() {} + + public byte[] acquire() { + int d = depth; + if (d > 0) { + depth = d - 1; + byte @Nullable [] buf = stack[d - 1]; + stack[d - 1] = null; + if (buf != null) { + return buf; + } + } + return new byte[SCRATCH_SIZE]; + } + + public void release(byte[] buf) { + int d = depth; + if (d < MAX_DEPTH) { + stack[d] = buf; + depth = d + 1; + } + } + } + + /** + * Per-thread re-entrancy-safe pool of {@code Object[]} reference buffers for wide nullable + * JavaBean encoders so getters are evaluated once per record without per-record heap allocation. + * Callers pass {@code usedLen} to {@link #release(Object[], int)} so references are cleared + * before pooling and never retained for GC. + */ + @Internal + public static final class RefScratchPool { + private static final int MAX_DEPTH = 8; + private static final int MAX_POOLED_SIZE = 512; + private final @Nullable Object[] @Nullable [] stack = new Object[MAX_DEPTH][]; + private int depth; + + RefScratchPool() {} + + public @Nullable Object[] acquire(int minSize) { + int d = depth; + if (d > 0) { + depth = d - 1; + @Nullable Object @Nullable [] buf = stack[d - 1]; + stack[d - 1] = null; + if (buf != null && buf.length >= minSize) { + return buf; + } + } + return new Object[minSize]; + } + + public void release(@Nullable Object[] buf, int usedLen) { + int d = depth; + if (d < MAX_DEPTH && buf.length <= MAX_POOLED_SIZE) { + Arrays.fill(buf, 0, usedLen, null); + stack[d] = buf; + depth = d + 1; + } + } + } + + @FunctionalInterface + private interface ElementReader { + T read(InputStream in, byte[] buf) throws IOException; + } + + private RowWireCodec() {} + + /** Returns the current thread's re-entrancy-safe scratch buffer pool. */ + public static ScratchPool scratchPool() { + ScratchPool pool = SCRATCH_POOL.get(); + if (pool == null) { + pool = new ScratchPool(); + SCRATCH_POOL.set(pool); + } + return pool; + } + + /** Returns the current thread's re-entrancy-safe reference array pool. */ + public static RefScratchPool refScratchPool() { + RefScratchPool pool = REF_SCRATCH_POOL.get(); + if (pool == null) { + pool = new RefScratchPool(); + REF_SCRATCH_POOL.set(pool); + } + return pool; + } + + /** Flushes any buffered bytes in {@code buf[0..pos)} to {@code out} and returns {@code 0}. */ + public static int flush(byte[] buf, int pos, OutputStream out) throws IOException { + if (pos > 0) { + out.write(buf, 0, pos); + } + return 0; + } + + private static int ensureRoom(byte[] buf, int pos, int needed, OutputStream out) + throws IOException { + if (pos + needed > SCRATCH_SIZE) { + out.write(buf, 0, pos); + return 0; + } + return pos; + } + + private static int putVarInt(byte[] buf, int pos, int v) { + return putVarLong(buf, pos, v & 0xFFFFFFFFL); + } + + private static int putVarLong(byte[] buf, int pos, long v) { + while ((v & ~0x7FL) != 0L) { + buf[pos++] = (byte) (((int) v & 0x7F) | 0x80); + v >>>= 7; + } + buf[pos++] = (byte) v; + return pos; + } + + private static int putBigEndianInt(byte[] buf, int pos, int v) { + INT_BE.set(buf, pos, v); + return pos + 4; + } + + private static int putBigEndianLong(byte[] buf, int pos, long v) { + LONG_BE.set(buf, pos, v); + return pos + 8; + } + + private static void readExact(InputStream in, byte[] buf, int len) throws IOException { + if (len == 0) { + return; + } + int n = in.read(buf, 0, len); + if (n != len) { + readExactSlow(in, buf, n, len); + } + } + + private static void readExactSlow(InputStream in, byte[] buf, int firstRead, int len) + throws IOException { + if (firstRead < 0) { + throw new CoderException(new EOFException()); + } + int off = firstRead; + while (off < len) { + int n = in.read(buf, off, len - off); + if (n < 0) { + throw new CoderException(new EOFException()); + } + off += n; + } + } + + public static void skipExact(InputStream in, int len) throws IOException { + if (len <= 0) { + return; + } + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int remaining = len; + while (remaining > 0) { + int chunk = Math.min(remaining, SCRATCH_SIZE); + int n = in.read(buf, 0, chunk); + if (n < 0) { + throw new CoderException(new EOFException()); + } + remaining -= n; + } + } finally { + pool.release(buf); + } + } + + /** + * Throws the exact runtime exception message emitted by {@code RowWithGetters} on null fields. + */ + public static RuntimeException nullNonNullableField(Schema schema, int fieldIndex) { + return new RuntimeException( + "Null value set on non-nullable field " + schema.getField(fieldIndex)); + } + + // ---- Headers and null masks ---- + + public static int packHeader(int fieldCount, long nullMask, byte[] buf, int pos, OutputStream out) + throws IOException { + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putVarInt(buf, pos, fieldCount); + if (nullMask == 0L) { + buf[pos++] = 0; + } else { + int numBytes = ((64 - Long.numberOfLeadingZeros(nullMask)) + 7) >>> 3; + buf[pos++] = (byte) numBytes; + for (int i = 0; i < numBytes; i++) { + buf[pos++] = (byte) (nullMask >>> (i << 3)); + } + } + return pos; + } + + /** + * Packs a {@code beam:coder:row:v1} header with a precomputed byte-array null bitmap into {@code + * buf}, falling back to direct stream writes only if the bitmap exceeds {@code buf} capacity. + */ + public static int packWideNullHeader( + int fieldCount, byte[] nullBytes, int nullByteLen, byte[] buf, OutputStream out) + throws IOException { + if (nullByteLen < 0) { + throw new CoderException("Invalid null bitset length: " + nullByteLen); + } + if (nullByteLen <= buf.length - MAX_HEADER_VARINT_BYTES) { + int pos = putVarInt(buf, 0, fieldCount); + pos = putVarInt(buf, pos, nullByteLen); + if (nullByteLen > 0) { + System.arraycopy(nullBytes, 0, buf, pos, nullByteLen); + } + return pos + nullByteLen; + } + writeVarInt(fieldCount, out); + writeVarInt(nullByteLen, out); + if (nullByteLen > 0) { + out.write(nullBytes, 0, nullByteLen); + } + return 0; + } + + /** + * Writes a 32-bit chunk null bitmask directly into {@code buf} at {@code hdrLen + chunkIdx * 4} + * in little-endian byte order and returns the updated highest non-zero null-bitmap byte length. + * Callers must guarantee {@code hdrLen + (chunkIdx + 1) * 4 <= buf.length}. + */ + public static int putChunkNullMask32( + byte[] buf, int hdrLen, int chunkIdx, int chunkMask, int highestNullByteLen) { + int base = chunkIdx << 2; + INT_LE.set(buf, hdrLen + base, chunkMask); + if (chunkMask != 0) { + return base + ((32 - Integer.numberOfLeadingZeros(chunkMask) + 7) >>> 3); + } + return highestNullByteLen; + } + + /** + * Patches the {@code beam:coder:row:v1} header prefix ({@code VarInt(fieldCount)} followed by a + * 1-byte {@code nullByteLen} in {@code [0, 127]}) in-place at the start of {@code buf} and + * returns the buffer position immediately after the null bitmap. + */ + public static int patchWideNullHeaderPrefix(byte[] buf, int fieldCount, int nullByteLen) { + int pos = putVarInt(buf, 0, fieldCount); + buf[pos++] = (byte) nullByteLen; + return pos + nullByteLen; + } + + /** + * Reads {@code nullByteLen} null-bitmap bytes into {@code scratchBuf} with zero allocation when + * {@code nullByteLen <= scratchBuf.length}, or into a freshly allocated array for >4096 fields. + */ + public static byte[] readNullBytes(InputStream in, int nullByteLen, byte[] scratchBuf) + throws IOException { + if (nullByteLen < 0) { + throw new CoderException("Invalid null bitset length: " + nullByteLen); + } + if (nullByteLen == 0) { + return scratchBuf; + } + byte[] target = nullByteLen <= scratchBuf.length ? scratchBuf : new byte[nullByteLen]; + readExact(in, target, nullByteLen); + return target; + } + + /** + * Extracts the 32-bit null bitmask for chunk {@code chunkIdx} (fields {@code [chunkIdx*32 .. + * chunkIdx*32 + 31]}) from {@code nullBytes[0..nullByteLen)}. + */ + public static int extractChunkNullMask32(byte[] nullBytes, int nullByteLen, int chunkIdx) { + int base = chunkIdx << 2; + if (base <= nullByteLen - 4) { + return (int) INT_LE.get(nullBytes, base); + } + if (base >= nullByteLen) { + return 0; + } + return extractChunkNullMask32Tail(nullBytes, nullByteLen, base); + } + + private static int extractChunkNullMask32Tail(byte[] nullBytes, int nullByteLen, int base) { + int m = nullBytes[base] & 0xFF; + if (base + 1 < nullByteLen) { + m |= (nullBytes[base + 1] & 0xFF) << 8; + if (base + 2 < nullByteLen) { + m |= (nullBytes[base + 2] & 0xFF) << 16; + } + } + return m; + } + + /** Returns whether bit {@code pos} is set in {@code nullBytes[0..nullByteLen)}. */ + public static boolean isNullBitSet(byte[] nullBytes, int nullByteLen, int pos) { + int byteIdx = pos >>> 3; + return byteIdx < nullByteLen && (nullBytes[byteIdx] & (1 << (pos & 7))) != 0; + } + + private static int fillNullBitmapFromArray( + Object[] arr, + int[] map, + boolean identityPositions, + int count, + byte[] target, + int targetOffset) { + int lastNonZero = -1; + int fullBytes = count >>> 3; + if (identityPositions) { + for (int bi = 0; bi < fullBytes; bi++) { + int p = bi << 3; + int b = 0; + if (arr[p] == null) { + b |= 1; + } + if (arr[p + 1] == null) { + b |= 2; + } + if (arr[p + 2] == null) { + b |= 4; + } + if (arr[p + 3] == null) { + b |= 8; + } + if (arr[p + 4] == null) { + b |= 16; + } + if (arr[p + 5] == null) { + b |= 32; + } + if (arr[p + 6] == null) { + b |= 64; + } + if (arr[p + 7] == null) { + b |= 128; + } + target[targetOffset + bi] = (byte) b; + if (b != 0) { + lastNonZero = bi; + } + } + int tailStart = fullBytes << 3; + if (tailStart < count) { + int b = 0; + for (int p = tailStart, bit = 1; p < count; p++, bit <<= 1) { + if (arr[p] == null) { + b |= bit; + } + } + target[targetOffset + fullBytes] = (byte) b; + if (b != 0) { + lastNonZero = fullBytes; + } + } + } else { + for (int bi = 0; bi < fullBytes; bi++) { + int p = bi << 3; + int b = 0; + if (arr[map[p]] == null) { + b |= 1; + } + if (arr[map[p + 1]] == null) { + b |= 2; + } + if (arr[map[p + 2]] == null) { + b |= 4; + } + if (arr[map[p + 3]] == null) { + b |= 8; + } + if (arr[map[p + 4]] == null) { + b |= 16; + } + if (arr[map[p + 5]] == null) { + b |= 32; + } + if (arr[map[p + 6]] == null) { + b |= 64; + } + if (arr[map[p + 7]] == null) { + b |= 128; + } + target[targetOffset + bi] = (byte) b; + if (b != 0) { + lastNonZero = bi; + } + } + int tailStart = fullBytes << 3; + if (tailStart < count) { + int b = 0; + for (int p = tailStart, bit = 1; p < count; p++, bit <<= 1) { + if (arr[map[p]] == null) { + b |= bit; + } + } + target[targetOffset + fullBytes] = (byte) b; + if (b != 0) { + lastNonZero = fullBytes; + } + } + } + return lastNonZero + 1; + } + + private static int fillNullBitmapFromList( + List list, + int[] map, + boolean identityPositions, + int count, + byte[] target, + int targetOffset) { + int lastNonZero = -1; + int fullBytes = count >>> 3; + if (identityPositions) { + for (int bi = 0; bi < fullBytes; bi++) { + int p = bi << 3; + int b = 0; + if (list.get(p) == null) { + b |= 1; + } + if (list.get(p + 1) == null) { + b |= 2; + } + if (list.get(p + 2) == null) { + b |= 4; + } + if (list.get(p + 3) == null) { + b |= 8; + } + if (list.get(p + 4) == null) { + b |= 16; + } + if (list.get(p + 5) == null) { + b |= 32; + } + if (list.get(p + 6) == null) { + b |= 64; + } + if (list.get(p + 7) == null) { + b |= 128; + } + target[targetOffset + bi] = (byte) b; + if (b != 0) { + lastNonZero = bi; + } + } + int tailStart = fullBytes << 3; + if (tailStart < count) { + int b = 0; + for (int p = tailStart, bit = 1; p < count; p++, bit <<= 1) { + if (list.get(p) == null) { + b |= bit; + } + } + target[targetOffset + fullBytes] = (byte) b; + if (b != 0) { + lastNonZero = fullBytes; + } + } + } else { + for (int bi = 0; bi < fullBytes; bi++) { + int p = bi << 3; + int b = 0; + if (list.get(map[p]) == null) { + b |= 1; + } + if (list.get(map[p + 1]) == null) { + b |= 2; + } + if (list.get(map[p + 2]) == null) { + b |= 4; + } + if (list.get(map[p + 3]) == null) { + b |= 8; + } + if (list.get(map[p + 4]) == null) { + b |= 16; + } + if (list.get(map[p + 5]) == null) { + b |= 32; + } + if (list.get(map[p + 6]) == null) { + b |= 64; + } + if (list.get(map[p + 7]) == null) { + b |= 128; + } + target[targetOffset + bi] = (byte) b; + if (b != 0) { + lastNonZero = bi; + } + } + int tailStart = fullBytes << 3; + if (tailStart < count) { + int b = 0; + for (int p = tailStart, bit = 1; p < count; p++, bit <<= 1) { + if (list.get(map[p]) == null) { + b |= bit; + } + } + target[targetOffset + fullBytes] = (byte) b; + if (b != 0) { + lastNonZero = fullBytes; + } + } + } + return lastNonZero + 1; + } + + /** + * Computes the null bitmap for a wide {@code Object[]} row (>64 fields) in a single forward pass + * and packs the header + bitmap into {@code buf} with zero heap allocation for schemas up to + * ~4000 fields. + */ + public static int packWideNullHeaderFromArray( + Object[] arr, int[] map, boolean identityPositions, int count, byte[] buf, OutputStream out) + throws IOException { + int maxBitmapBytes = (count + 7) >>> 3; + if (maxBitmapBytes > buf.length - MAX_HEADER_VARINT_BYTES) { + return packHugeNullHeaderFromArray(arr, map, identityPositions, count, maxBitmapBytes, out); + } + int countVarLen = VarInt.getLength(count); + int hdrReserve = countVarLen + VarInt.getLength(maxBitmapBytes); + int numBytes = fillNullBitmapFromArray(arr, map, identityPositions, count, buf, hdrReserve); + int hdrPos = putVarInt(buf, 0, count); + hdrPos = putVarInt(buf, hdrPos, numBytes); + if (hdrPos != hdrReserve && numBytes > 0) { + System.arraycopy(buf, hdrReserve, buf, hdrPos, numBytes); + } + return hdrPos + numBytes; + } + + private static int packHugeNullHeaderFromArray( + Object[] arr, + int[] map, + boolean identityPositions, + int count, + int maxBitmapBytes, + OutputStream out) + throws IOException { + byte[] bitmap = new byte[maxBitmapBytes]; + int numBytes = fillNullBitmapFromArray(arr, map, identityPositions, count, bitmap, 0); + writeVarInt(count, out); + writeVarInt(numBytes, out); + if (numBytes > 0) { + out.write(bitmap, 0, numBytes); + } + return 0; + } + + /** + * Computes the null bitmap for a wide {@code List} row (>64 fields) in a single forward + * pass and packs the header + bitmap into {@code buf} with zero heap allocation for schemas up to + * ~4000 fields. + */ + public static int packWideNullHeaderFromList( + List list, + int[] map, + boolean identityPositions, + int count, + byte[] buf, + OutputStream out) + throws IOException { + int maxBitmapBytes = (count + 7) >>> 3; + if (maxBitmapBytes > buf.length - MAX_HEADER_VARINT_BYTES) { + return packHugeNullHeaderFromList(list, map, identityPositions, count, maxBitmapBytes, out); + } + int countVarLen = VarInt.getLength(count); + int hdrReserve = countVarLen + VarInt.getLength(maxBitmapBytes); + int numBytes = fillNullBitmapFromList(list, map, identityPositions, count, buf, hdrReserve); + int hdrPos = putVarInt(buf, 0, count); + hdrPos = putVarInt(buf, hdrPos, numBytes); + if (hdrPos != hdrReserve && numBytes > 0) { + System.arraycopy(buf, hdrReserve, buf, hdrPos, numBytes); + } + return hdrPos + numBytes; + } + + private static int packHugeNullHeaderFromList( + List list, + int[] map, + boolean identityPositions, + int count, + int maxBitmapBytes, + OutputStream out) + throws IOException { + byte[] bitmap = new byte[maxBitmapBytes]; + int numBytes = fillNullBitmapFromList(list, map, identityPositions, count, bitmap, 0); + writeVarInt(count, out); + writeVarInt(numBytes, out); + if (numBytes > 0) { + out.write(bitmap, 0, numBytes); + } + return 0; + } + + public static void writeHeader(int fieldCount, long nullMask, OutputStream out) + throws IOException { + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int pos = packHeader(fieldCount, nullMask, buf, 0, out); + out.write(buf, 0, pos); + } finally { + pool.release(buf); + } + } + + public static long readNullMask(InputStream in, int nullByteLen, byte[] buf) throws IOException { + if (nullByteLen < 0 || nullByteLen > 8) { + throw new CoderException("Invalid 64-bit null bitset length: " + nullByteLen); + } + if (nullByteLen == 0) { + return 0L; + } + if (buf.length < nullByteLen) { + throw new CoderException("Scratch buffer too small for null bitset: " + buf.length); + } + readExact(in, buf, nullByteLen); + long mask = 0L; + for (int i = 0; i < nullByteLen; i++) { + mask |= (buf[i] & 0xFFL) << (i << 3); + } + return mask; + } + + // ---- Primitives (buffered pack* + buf-accepting read*) ---- + + public static int packByte(byte v, byte[] buf, int pos, OutputStream out) throws IOException { + if (pos >= SCRATCH_SIZE) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = v; + return pos; + } + + public static byte readByte(InputStream in) throws IOException { + int b = in.read(); + if (b >= 0) { + return (byte) b; + } + throw eofException(); + } + + private static CoderException eofException() { + return new CoderException(new EOFException()); + } + + private static IOException varIntNotTerminated() { + return new IOException("varint not terminated"); + } + + private static IOException varIntTooLong() { + return new IOException("varint too long"); + } + + public static int packBoolean(boolean v, byte[] buf, int pos, OutputStream out) + throws IOException { + if (pos >= SCRATCH_SIZE) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = (byte) (v ? 1 : 0); + return pos; + } + + public static boolean readBoolean(InputStream in) throws IOException { + int bv = in.read(); + if ((bv & ~1) == 0) { + return bv != 0; + } + throw invalidBoolean(bv); + } + + private static IOException invalidBoolean(int bv) { + if (bv < 0) { + return new CoderException(new EOFException()); + } + return new IOException(String.format("Expected 0 or 1, got %d", (byte) bv)); + } + + public static int packInt16(short v, byte[] buf, int pos, OutputStream out) throws IOException { + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + SHORT_BE.set(buf, pos, v); + return pos + 2; + } + + public static short readInt16(InputStream in, byte[] buf) throws IOException { + readExact(in, buf, 2); + return (short) SHORT_BE.get(buf, 0); + } + + private static int readBigEndianInt(InputStream in, byte[] buf) throws IOException { + readExact(in, buf, 4); + return (int) INT_BE.get(buf, 0); + } + + public static long readBigEndianLong(InputStream in, byte[] buf) throws IOException { + readExact(in, buf, 8); + return (long) LONG_BE.get(buf, 0); + } + + public static int packVarInt(int v, byte[] buf, int pos, OutputStream out) throws IOException { + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + if ((v & ~0x7F) == 0) { + buf[pos++] = (byte) v; + return pos; + } + return putVarInt(buf, pos, v); + } + + public static void writeVarInt(int v, OutputStream out) throws IOException { + if ((v & ~0x7F) == 0) { + out.write(v); + return; + } + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int len = putVarInt(buf, 0, v); + out.write(buf, 0, len); + } finally { + pool.release(buf); + } + } + + public static int readVarInt(InputStream in) throws IOException { + int b0 = in.read(); + if ((b0 & ~0x7F) == 0) { + return b0; + } + return readVarIntSlow(b0, in); + } + + private static int readVarIntSlow(int b0, InputStream in) throws IOException { + if (b0 < 0) { + throw eofException(); + } + int b1 = in.read(); + if ((b1 & ~0x7F) == 0) { + return (b0 & 0x7F) | (b1 << 7); + } + return readVarInt3to5(b0, b1, in); + } + + private static int readVarInt3to5(int b0, int b1, InputStream in) throws IOException { + if (b1 < 0) { + throw varIntNotTerminated(); + } + int r = (b0 & 0x7F) | ((b1 & 0x7F) << 7); + int b2 = in.read(); + if ((b2 & ~0x7F) == 0) { + return r | (b2 << 14); + } + if (b2 < 0) { + throw varIntNotTerminated(); + } + r |= (b2 & 0x7F) << 14; + int b3 = in.read(); + if ((b3 & ~0x7F) == 0) { + return r | (b3 << 21); + } + if (b3 < 0) { + throw varIntNotTerminated(); + } + r |= (b3 & 0x7F) << 21; + int b4 = in.read(); + if ((b4 & ~0x0F) == 0) { + return r | (b4 << 28); + } + return readVarIntOverflowOrError(r, b4, in); + } + + private static int readVarIntOverflowOrError(int low28, int b4, InputStream in) + throws IOException { + long r; + if ((b4 & ~0x7F) == 0) { + r = (low28 & 0xFFFFFFFFL) | ((long) b4 << 28); + } else { + r = readVarLongTail(low28 & 0xFFFFFFFFL, b4, in); + } + if (r < 0L || r >= (1L << 32)) { + throw new IOException("varint overflow " + r); + } + return (int) r; + } + + public static int packVarLong(long v, byte[] buf, int pos, OutputStream out) throws IOException { + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + if ((v & ~0x7FL) == 0L) { + buf[pos++] = (byte) v; + return pos; + } + return putVarLong(buf, pos, v); + } + + private static void writeVarLong(long v, OutputStream out) throws IOException { + if ((v & ~0x7FL) == 0L) { + out.write((int) v); + return; + } + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int len = putVarLong(buf, 0, v); + out.write(buf, 0, len); + } finally { + pool.release(buf); + } + } + + public static long readVarLong(InputStream in) throws IOException { + int b0 = in.read(); + if ((b0 & ~0x7F) == 0) { + return b0; + } + return readVarLongSlow(b0, in); + } + + private static long readVarLongSlow(int b0, InputStream in) throws IOException { + if (b0 < 0) { + throw eofException(); + } + int b1 = in.read(); + if ((b1 & ~0x7F) == 0) { + return (b0 & 0x7F) | (b1 << 7); + } + if (b1 < 0) { + throw varIntNotTerminated(); + } + int lo = (b0 & 0x7F) | ((b1 & 0x7F) << 7); + int b2 = in.read(); + if ((b2 & ~0x7F) == 0) { + return lo | (b2 << 14); + } + if (b2 < 0) { + throw varIntNotTerminated(); + } + lo |= (b2 & 0x7F) << 14; + int b3 = in.read(); + if ((b3 & ~0x7F) == 0) { + return lo | (b3 << 21); + } + if (b3 < 0) { + throw varIntNotTerminated(); + } + long res = lo | ((b3 & 0x7F) << 21); + int b4 = in.read(); + if ((b4 & ~0x7F) == 0) { + return res | ((long) b4 << 28); + } + return readVarLongTail(res, b4, in); + } + + private static long readVarLongTail(long res, int b4, InputStream in) throws IOException { + if (b4 < 0) { + throw varIntNotTerminated(); + } + res |= (b4 & 0x7FL) << 28; + int shift = 35; + int b; + do { + b = in.read(); + if (b < 0) { + throw varIntNotTerminated(); + } + long bits = b & 0x7FL; + if (shift >= 64 || (shift == 63 && bits > 1L)) { + throw varIntTooLong(); + } + res |= bits << shift; + shift += 7; + } while ((b & 0x80) != 0); + return res; + } + + public static int packFloat(float v, byte[] buf, int pos, OutputStream out) throws IOException { + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + return putBigEndianInt(buf, pos, Float.floatToIntBits(v)); + } + + public static float readFloat(InputStream in, byte[] buf) throws IOException { + return Float.intBitsToFloat(readBigEndianInt(in, buf)); + } + + public static int packDouble(double v, byte[] buf, int pos, OutputStream out) throws IOException { + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + return putBigEndianLong(buf, pos, Double.doubleToLongBits(v)); + } + + public static double readDouble(InputStream in, byte[] buf) throws IOException { + return Double.longBitsToDouble(readBigEndianLong(in, buf)); + } + + public static int packDateTime(@Nullable ReadableInstant v, byte[] buf, int pos, OutputStream out) + throws IOException { + if (v == null) { + throw new CoderException("cannot encode a null Instant"); + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + return putBigEndianLong(buf, pos, v.getMillis() - Long.MIN_VALUE); + } + + public static Instant readDateTime(InputStream in, byte[] buf) throws IOException { + return new Instant(readBigEndianLong(in, buf) + Long.MIN_VALUE); + } + + // ---- Variable-length scalars ---- + + public static int packString(@Nullable String s, byte[] buf, int pos, OutputStream out) + throws IOException { + if (s == null) { + throw new CoderException("cannot encode a null String"); + } + int len = s.length(); + if (len == 0) { + if (pos >= SCRATCH_SIZE) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = 0; + return pos; + } + if (len <= MAX_ASCII_STRING_FAST) { + int hdr = len < 128 ? 1 : 2; + pos = ensureRoom(buf, pos, hdr + len, out); + int savedPos = pos; + if (hdr == 1) { + buf[pos] = (byte) len; + } else { + buf[pos] = (byte) ((len & 0x7F) | 0x80); + buf[pos + 1] = (byte) (len >> 7); + } + int start = pos + hdr; + for (int i = 0; i < len; i++) { + char c = s.charAt(i); + if (c >= 0x80) { + if (savedPos > 0) { + out.write(buf, 0, savedPos); + } + writeStringUtf8Slow(s, buf, out); + return 0; + } + buf[start + i] = (byte) c; + } + return start + len; + } + if (pos > 0) { + out.write(buf, 0, pos); + } + writeStringUtf8Slow(s, buf, out); + return 0; + } + + private static void writeStringUtf8Slow(String s, byte[] buf, OutputStream out) + throws IOException { + byte[] utf8 = s.getBytes(StandardCharsets.UTF_8); + int n = putVarInt(buf, 0, utf8.length); + out.write(buf, 0, n); + out.write(utf8); + } + + public static String readString(InputStream in, byte[] buf) throws IOException { + int len = readVarInt(in); + if (len > 0 && len <= SCRATCH_SIZE) { + readExact(in, buf, len); + return new String(buf, 0, len, StandardCharsets.UTF_8); + } + return readStringSlow(in, len); + } + + private static String readStringSlow(InputStream in, int len) throws IOException { + if (len == 0) { + return ""; + } + if (len < 0) { + throw new CoderException("Invalid encoded string length: " + len); + } + byte[] bytes = new byte[len]; + readExact(in, bytes, len); + return new String(bytes, StandardCharsets.UTF_8); + } + + public static int packBytes(byte @Nullable [] bytes, byte[] buf, int pos, OutputStream out) + throws IOException { + if (bytes == null) { + throw new CoderException("cannot encode a null byte[]"); + } + int len = bytes.length; + if (len == 0) { + if (pos >= SCRATCH_SIZE) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = 0; + return pos; + } + if (len <= MAX_INLINE_BYTES_FAST) { + pos = ensureRoom(buf, pos, len + 2, out); + pos = putVarInt(buf, pos, len); + System.arraycopy(bytes, 0, buf, pos, len); + return pos + len; + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putVarInt(buf, pos, len); + out.write(buf, 0, pos); + out.write(bytes); + return 0; + } + + public static byte[] readBytes(InputStream in) throws IOException { + int len = readVarInt(in); + if (len > 0) { + byte[] bytes = new byte[len]; + readExact(in, bytes, len); + return bytes; + } + return readEmptyOrInvalidBytes(len); + } + + private static byte[] readEmptyOrInvalidBytes(int len) throws IOException { + if (len == 0) { + return EMPTY_BYTES; + } + throw new CoderException("Invalid encoded byte[] length: " + len); + } + + public static int packDecimal(@Nullable BigDecimal bd, byte[] buf, int pos, OutputStream out) + throws IOException { + if (bd == null) { + throw new NullPointerException(); + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + int scale = bd.scale(); + BigInteger unscaled = bd.unscaledValue(); + int bitLen = unscaled.bitLength(); + if (bitLen <= 63) { + long v = unscaled.longValue(); + int byteLen = (bitLen >>> 3) + 1; + pos = putVarInt(buf, pos, scale); + buf[pos++] = (byte) byteLen; + for (int i = byteLen - 1; i >= 0; i--) { + buf[pos++] = (byte) (v >>> (i << 3)); + } + return pos; + } + byte[] mag = unscaled.toByteArray(); + pos = putVarInt(buf, pos, scale); + pos = putVarInt(buf, pos, mag.length); + out.write(buf, 0, pos); + out.write(mag); + return 0; + } + + public static BigDecimal readDecimal(InputStream in, byte[] buf) throws IOException { + int scale = readVarInt(in); + int len = readVarInt(in); + if (len < 0) { + throw new IOException("invalid length " + len); + } + if (len >= 1 && len <= 8) { + readExact(in, buf, len); + long unscaled = buf[0]; + for (int i = 1; i < len; i++) { + unscaled = (unscaled << 8) | (buf[i] & 0xFFL); + } + return BigDecimal.valueOf(unscaled, scale); + } + byte[] bytes = len == 0 ? EMPTY_BYTES : new byte[len]; + if (len > 0) { + readExact(in, bytes, len); + } + return new BigDecimal(new BigInteger(bytes), scale); + } + + // ---- Built-in logical types ---- + + private static void expectTwoNonNullFields( + InputStream in, String typeName, boolean illegalStateOnMissing) throws IOException { + int b0 = in.read(); + if (b0 == 2) { + int b1 = in.read(); + if (b1 == 0) { + return; + } + if (b1 < 0) { + throw new CoderException(new EOFException()); + } + int nullLen = (b1 & 0x80) == 0 ? b1 : readVarIntSlow(b1, in); + checkTwoFieldNullBitmap(in, nullLen, typeName, illegalStateOnMissing); + return; + } + if (b0 < 0) { + throw new CoderException(new EOFException()); + } + int fieldCount = (b0 & 0x80) == 0 ? b0 : readVarIntSlow(b0, in); + int nullLen = readVarInt(in); + checkTwoFieldNullBitmap(in, nullLen, typeName, illegalStateOnMissing); + if (fieldCount < 2) { + String msg = + "While trying to convert to " + typeName + ": Row expected 2 fields, got " + fieldCount; + if (illegalStateOnMissing) { + throw new IllegalStateException(msg); + } + throw new IllegalArgumentException(msg); + } + } + + private static void checkTwoFieldNullBitmap( + InputStream in, int nullLen, String typeName, boolean illegalStateOnMissing) + throws IOException { + if (nullLen < 0) { + throw new CoderException("Negative null bitset length: " + nullLen); + } + if (nullLen == 0) { + return; + } + int firstNullByte = in.read(); + if (firstNullByte < 0) { + throw new CoderException(new EOFException()); + } + if (nullLen > 1) { + skipExact(in, nullLen - 1); + } + if ((firstNullByte & 0x03) != 0) { + String msg = "While trying to convert to " + typeName + ": Row missing required field"; + if (illegalStateOnMissing) { + throw new IllegalStateException(msg); + } + throw new IllegalArgumentException(msg); + } + } + + public static int packLocalDate(@Nullable LocalDate value, byte[] buf, int pos, OutputStream out) + throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null LocalDate"); + } + return packVarLong(value.toEpochDay(), buf, pos, out); + } + + public static void writeLocalDate(@Nullable LocalDate value, OutputStream out) + throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null LocalDate"); + } + writeVarLong(value.toEpochDay(), out); + } + + public static LocalDate readLocalDate(InputStream in) throws IOException { + return LocalDate.ofEpochDay(readVarLong(in)); + } + + public static int packLocalTime(@Nullable LocalTime value, byte[] buf, int pos, OutputStream out) + throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null LocalTime"); + } + return packVarLong(value.toNanoOfDay(), buf, pos, out); + } + + public static void writeLocalTime(@Nullable LocalTime value, OutputStream out) + throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null LocalTime"); + } + writeVarLong(value.toNanoOfDay(), out); + } + + public static LocalTime readLocalTime(InputStream in) throws IOException { + return LocalTime.ofNanoOfDay(readVarLong(in)); + } + + public static int packLocalDateTime( + @Nullable LocalDateTime value, byte[] buf, int pos, OutputStream out) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null LocalDateTime"); + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = 2; + buf[pos++] = 0; + pos = putVarLong(buf, pos, value.toLocalDate().toEpochDay()); + return putVarLong(buf, pos, value.toLocalTime().toNanoOfDay()); + } + + public static void writeLocalDateTime(@Nullable LocalDateTime value, OutputStream out) + throws IOException { + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int pos = packLocalDateTime(value, buf, 0, out); + out.write(buf, 0, pos); + } finally { + pool.release(buf); + } + } + + public static LocalDateTime readLocalDateTime(InputStream in) throws IOException { + expectTwoNonNullFields(in, "LocalDateTime", false); + long epochDay = readVarLong(in); + long nanoOfDay = readVarLong(in); + return LocalDateTime.of(LocalDate.ofEpochDay(epochDay), LocalTime.ofNanoOfDay(nanoOfDay)); + } + + public static int packUuid(@Nullable UUID value, byte[] buf, int pos, OutputStream out) + throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null UUID"); + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = 2; + buf[pos++] = 0; + pos = putVarLong(buf, pos, value.getMostSignificantBits()); + return putVarLong(buf, pos, value.getLeastSignificantBits()); + } + + public static void writeUuid(@Nullable UUID value, OutputStream out) throws IOException { + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int pos = packUuid(value, buf, 0, out); + out.write(buf, 0, pos); + } finally { + pool.release(buf); + } + } + + public static UUID readUuid(InputStream in) throws IOException { + expectTwoNonNullFields(in, "UUID", true); + long msb = readVarLong(in); + long lsb = readVarLong(in); + return new UUID(msb, lsb); + } + + public static int packNanosInstant( + java.time.@Nullable Instant value, byte[] buf, int pos, OutputStream out) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null Instant"); + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = 2; + buf[pos++] = 0; + pos = putVarLong(buf, pos, value.getEpochSecond()); + return putVarInt(buf, pos, value.getNano()); + } + + public static void writeNanosInstant(java.time.@Nullable Instant value, OutputStream out) + throws IOException { + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int pos = packNanosInstant(value, buf, 0, out); + out.write(buf, 0, pos); + } finally { + pool.release(buf); + } + } + + public static java.time.Instant readNanosInstant(InputStream in) throws IOException { + expectTwoNonNullFields(in, "Instant", false); + long seconds = readVarLong(in); + int nanos = readVarInt(in); + return java.time.Instant.ofEpochSecond(seconds, nanos); + } + + public static int packMicrosInstant( + java.time.@Nullable Instant value, byte[] buf, int pos, OutputStream out) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null Instant"); + } + int nano = value.getNano(); + if (nano % 1000 != 0) { + throw new AssertionError( + "micros_instant logical type encountered a Java " + + "Instant with greater than microsecond precision."); + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = 2; + buf[pos++] = 0; + pos = putVarLong(buf, pos, value.getEpochSecond()); + return putVarInt(buf, pos, nano / 1000); + } + + public static void writeMicrosInstant(java.time.@Nullable Instant value, OutputStream out) + throws IOException { + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int pos = packMicrosInstant(value, buf, 0, out); + out.write(buf, 0, pos); + } finally { + pool.release(buf); + } + } + + public static java.time.Instant readMicrosInstant(InputStream in) throws IOException { + expectTwoNonNullFields(in, "Instant", false); + long seconds = readVarLong(in); + int micros = readVarInt(in); + return java.time.Instant.ofEpochSecond(seconds, micros * 1000L); + } + + public static int packNanosDuration( + @Nullable Duration value, byte[] buf, int pos, OutputStream out) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null Duration"); + } + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + buf[pos++] = 2; + buf[pos++] = 0; + pos = putVarLong(buf, pos, value.getSeconds()); + return putVarInt(buf, pos, value.getNano()); + } + + public static void writeNanosDuration(@Nullable Duration value, OutputStream out) + throws IOException { + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + int pos = packNanosDuration(value, buf, 0, out); + out.write(buf, 0, pos); + } finally { + pool.release(buf); + } + } + + public static Duration readNanosDuration(InputStream in) throws IOException { + expectTwoNonNullFields(in, "Duration", false); + long seconds = readVarLong(in); + int nanos = readVarInt(in); + return Duration.ofSeconds(seconds, nanos); + } + + public static void writeTimestamp( + java.time.@Nullable Instant value, int precision, OutputStream out) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null Instant"); + } + int scalingFactor = TIMESTAMP_SCALING_FACTORS[precision]; + int nano = value.getNano(); + int subseconds; + if (scalingFactor == 1) { + subseconds = nano; + } else { + if (nano % scalingFactor != 0) { + throw new IllegalStateException( + String.format( + "Timestamp logical type was configured with precision %s, but encountered " + + "a Java Instant with %s nanoseconds (not evenly divisible by scaling factor %s).", + precision, nano, scalingFactor)); + } + subseconds = nano / scalingFactor; + } + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + buf[0] = 2; + buf[1] = 0; + int pos = putVarLong(buf, 2, value.getEpochSecond()); + if (precision < 5) { + short s = (short) subseconds; + buf[pos++] = (byte) (s >>> 8); + buf[pos++] = (byte) s; + } else { + pos = putVarInt(buf, pos, subseconds); + } + out.write(buf, 0, pos); + } finally { + pool.release(buf); + } + } + + public static java.time.Instant readTimestamp(int precision, InputStream in) throws IOException { + expectTwoNonNullFields(in, "Instant", false); + long seconds = readVarLong(in); + long subseconds; + if (precision < 5) { + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + subseconds = readInt16(in, buf); + } finally { + pool.release(buf); + } + } else { + subseconds = readVarInt(in); + } + if (subseconds < 0) { + throw new IllegalArgumentException( + String.format( + "While trying to convert to Instant: subseconds field must be non-negative, " + + "but was %s. This likely indicates data corruption.", + subseconds)); + } + int maxSubseconds = TIMESTAMP_MAX_SUBSECONDS[precision]; + if (subseconds > maxSubseconds) { + throw new IllegalArgumentException( + String.format( + "While trying to convert to Instant: subseconds field must be <= %s for precision %s, " + + "but was %s. This likely indicates data corruption or precision mismatch.", + maxSubseconds, precision, subseconds)); + } + return java.time.Instant.ofEpochSecond( + seconds, subseconds * TIMESTAMP_SCALING_FACTORS[precision]); + } + + // ---- Wire-exact non-nullable container codecs (match ListCoder / MapCoder bit-for-bit) ---- + + private static List readChunkedList( + InputStream in, byte[] buf, ElementReader elementReader) throws IOException { + ArrayList out = new ArrayList<>(); + long count = readVarLong(in); + while (count > 0L) { + out.add(elementReader.read(in, buf)); + --count; + if (count == 0L) { + count = readVarLong(in); + } + } + if (count != 0L) { + throw new IllegalStateException( + String.format( + "List does not support non zero terminator values. Received stream with terminator %s.", + count)); + } + return out; + } + + public static int packStringCollection( + @Nullable Collection col, byte[] buf, int pos, OutputStream out) throws IOException { + if (col == null) { + throw new CoderException("cannot encode a null List"); + } + int size = col.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0; i < size; i++) { + pos = packString(list.get(i), buf, pos, out); + } + } else { + for (String s : col) { + pos = packString(s, buf, pos, out); + } + } + return pos; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static int packStringIterable( + Iterable iter, byte[] buf, int pos, OutputStream out, Coder fallback) + throws IOException { + if (iter instanceof Collection) { + return packStringCollection((Collection) iter, buf, pos, out); + } + if (pos > 0) { + out.write(buf, 0, pos); + } + fallback.encode(iter, out); + return 0; + } + + public static List readStringList(InputStream in, byte[] buf) throws IOException { + int size = readBigEndianInt(in, buf); + if (size >= 0) { + ArrayList out = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + out.add(readString(in, buf)); + } + return out; + } + return readChunkedList(in, buf, RowWireCodec::readString); + } + + public static int packInt32Collection( + @Nullable Collection col, byte[] buf, int pos, OutputStream out) throws IOException { + if (col == null) { + throw new CoderException("cannot encode a null List"); + } + int size = col.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0; i < size; i++) { + Integer v = list.get(i); + if (v == null) { + throw new CoderException("cannot encode a null Integer"); + } + pos = packVarInt(v, buf, pos, out); + } + } else { + for (Integer v : col) { + if (v == null) { + throw new CoderException("cannot encode a null Integer"); + } + pos = packVarInt(v, buf, pos, out); + } + } + return pos; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static int packInt32Iterable( + Iterable iter, byte[] buf, int pos, OutputStream out, Coder fallback) + throws IOException { + if (iter instanceof Collection) { + return packInt32Collection((Collection) iter, buf, pos, out); + } + if (pos > 0) { + out.write(buf, 0, pos); + } + fallback.encode(iter, out); + return 0; + } + + public static List readInt32List(InputStream in, byte[] buf) throws IOException { + int size = readBigEndianInt(in, buf); + if (size >= 0) { + ArrayList out = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + out.add(readVarInt(in)); + } + return out; + } + return readChunkedList(in, buf, (stream, b) -> readVarInt(stream)); + } + + public static int packInt64Collection( + @Nullable Collection col, byte[] buf, int pos, OutputStream out) throws IOException { + if (col == null) { + throw new CoderException("cannot encode a null List"); + } + int size = col.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0; i < size; i++) { + Long v = list.get(i); + if (v == null) { + throw new CoderException("cannot encode a null Long"); + } + pos = packVarLong(v, buf, pos, out); + } + } else { + for (Long v : col) { + if (v == null) { + throw new CoderException("cannot encode a null Long"); + } + pos = packVarLong(v, buf, pos, out); + } + } + return pos; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static int packInt64Iterable( + Iterable iter, byte[] buf, int pos, OutputStream out, Coder fallback) + throws IOException { + if (iter instanceof Collection) { + return packInt64Collection((Collection) iter, buf, pos, out); + } + if (pos > 0) { + out.write(buf, 0, pos); + } + fallback.encode(iter, out); + return 0; + } + + public static List readInt64List(InputStream in, byte[] buf) throws IOException { + int size = readBigEndianInt(in, buf); + if (size >= 0) { + ArrayList out = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + out.add(readVarLong(in)); + } + return out; + } + return readChunkedList(in, buf, (stream, b) -> readVarLong(stream)); + } + + public static int packDoubleCollection( + @Nullable Collection col, byte[] buf, int pos, OutputStream out) throws IOException { + if (col == null) { + throw new CoderException("cannot encode a null List"); + } + int size = col.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0; i < size; i++) { + Double v = list.get(i); + if (v == null) { + throw new CoderException("cannot encode a null Double"); + } + pos = packDouble(v, buf, pos, out); + } + } else { + for (Double v : col) { + if (v == null) { + throw new CoderException("cannot encode a null Double"); + } + pos = packDouble(v, buf, pos, out); + } + } + return pos; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static int packDoubleIterable( + Iterable iter, byte[] buf, int pos, OutputStream out, Coder fallback) + throws IOException { + if (iter instanceof Collection) { + return packDoubleCollection((Collection) iter, buf, pos, out); + } + if (pos > 0) { + out.write(buf, 0, pos); + } + fallback.encode(iter, out); + return 0; + } + + public static List readDoubleList(InputStream in, byte[] buf) throws IOException { + int size = readBigEndianInt(in, buf); + if (size >= 0) { + ArrayList out = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + out.add(readDouble(in, buf)); + } + return out; + } + return readChunkedList(in, buf, RowWireCodec::readDouble); + } + + /** Encodes any {@link Collection} with an element {@link Coder}, avoiding iterator allocation. */ + public static void writeElementCollection( + @Nullable Collection col, Coder elemCoder, OutputStream out) throws IOException { + if (col == null) { + throw new CoderException("cannot encode a null List"); + } + int size = col.size(); + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + putBigEndianInt(buf, 0, size); + out.write(buf, 0, 4); + } finally { + pool.release(buf); + } + if (size == 0) { + return; + } + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0; i < size; i++) { + elemCoder.encode(list.get(i), out); + } + } else { + for (T elem : col) { + elemCoder.encode(elem, out); + } + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static void writeElementIterable( + Iterable iter, Coder elemCoder, OutputStream out, Coder fallback) throws IOException { + if (iter instanceof Collection) { + writeElementCollection((Collection) iter, elemCoder, out); + } else { + fallback.encode(iter, out); + } + } + + public static List readElementList(InputStream in, Coder elemCoder) throws IOException { + int size; + ScratchPool pool = scratchPool(); + byte[] buf = pool.acquire(); + try { + size = readBigEndianInt(in, buf); + } finally { + pool.release(buf); + } + if (size >= 0) { + ArrayList out = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + out.add(elemCoder.decode(in)); + } + return out; + } + return readChunkedList(in, EMPTY_BYTES, (stream, ignored) -> elemCoder.decode(stream)); + } + + public static int packStringLongMap( + @Nullable Map map, byte[] buf, int pos, OutputStream out) throws IOException { + if (map == null) { + throw new CoderException("cannot encode a null Map"); + } + int size = map.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + for (Map.Entry e : map.entrySet()) { + pos = packString(e.getKey(), buf, pos, out); + Long v = e.getValue(); + if (v == null) { + throw new CoderException("cannot encode a null Long"); + } + pos = packVarLong(v, buf, pos, out); + } + return pos; + } + + public static Map readStringLongMap(InputStream in, byte[] buf) throws IOException { + int size = readBigEndianInt(in, buf); + if (size == 0) { + return Collections.emptyMap(); + } + if (size < 0) { + throw new CoderException("Invalid map size: " + size); + } + Map map = Maps.newHashMapWithExpectedSize(size); + for (int i = 0; i < size; i++) { + String k = readString(in, buf); + long v = readVarLong(in); + map.put(k, v); + } + return map; + } + + public static int packStringStringMap( + @Nullable Map map, byte[] buf, int pos, OutputStream out) throws IOException { + if (map == null) { + throw new CoderException("cannot encode a null Map"); + } + int size = map.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + for (Map.Entry e : map.entrySet()) { + pos = packString(e.getKey(), buf, pos, out); + pos = packString(e.getValue(), buf, pos, out); + } + return pos; + } + + public static Map readStringStringMap(InputStream in, byte[] buf) + throws IOException { + int size = readBigEndianInt(in, buf); + if (size == 0) { + return Collections.emptyMap(); + } + if (size < 0) { + throw new CoderException("Invalid map size: " + size); + } + Map map = Maps.newHashMapWithExpectedSize(size); + for (int i = 0; i < size; i++) { + map.put(readString(in, buf), readString(in, buf)); + } + return map; + } + + public static int packStringIntMap( + @Nullable Map map, byte[] buf, int pos, OutputStream out) + throws IOException { + if (map == null) { + throw new CoderException("cannot encode a null Map"); + } + int size = map.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + for (Map.Entry e : map.entrySet()) { + pos = packString(e.getKey(), buf, pos, out); + Integer v = e.getValue(); + if (v == null) { + throw new CoderException("cannot encode a null Integer"); + } + pos = packVarInt(v, buf, pos, out); + } + return pos; + } + + public static Map readStringIntMap(InputStream in, byte[] buf) + throws IOException { + int size = readBigEndianInt(in, buf); + if (size == 0) { + return Collections.emptyMap(); + } + if (size < 0) { + throw new CoderException("Invalid map size: " + size); + } + Map map = Maps.newHashMapWithExpectedSize(size); + for (int i = 0; i < size; i++) { + String k = readString(in, buf); + int v = readVarInt(in); + map.put(k, v); + } + return map; + } + + public static int packStringDoubleMap( + @Nullable Map map, byte[] buf, int pos, OutputStream out) throws IOException { + if (map == null) { + throw new CoderException("cannot encode a null Map"); + } + int size = map.size(); + if (pos >= FLUSH_LIMIT) { + out.write(buf, 0, pos); + pos = 0; + } + pos = putBigEndianInt(buf, pos, size); + if (size == 0) { + return pos; + } + for (Map.Entry e : map.entrySet()) { + pos = packString(e.getKey(), buf, pos, out); + Double v = e.getValue(); + if (v == null) { + throw new CoderException("cannot encode a null Double"); + } + pos = packDouble(v, buf, pos, out); + } + return pos; + } + + public static Map readStringDoubleMap(InputStream in, byte[] buf) + throws IOException { + int size = readBigEndianInt(in, buf); + if (size == 0) { + return Collections.emptyMap(); + } + if (size < 0) { + throw new CoderException("Invalid map size: " + size); + } + Map map = Maps.newHashMapWithExpectedSize(size); + for (int i = 0; i < size; i++) { + String k = readString(in, buf); + double v = readDouble(in, buf); + map.put(k, v); + } + return map; + } + + // ---- Zero-allocation byte size helpers ---- + + private static int utf8EncodedLength(String s) { + int len = s.length(); + int i = 0; + while (i < len && s.charAt(i) < 0x80) { + i++; + } + if (i == len) { + return len; + } + try { + return Utf8.encodedLength(s); + } catch (IllegalArgumentException e) { + return s.getBytes(StandardCharsets.UTF_8).length; + } + } + + public static long sizeOfString(String s) { + int len = utf8EncodedLength(s); + return (long) VarInt.getLength(len) + len; + } + + public static long sizeOfBytes(byte[] bytes) { + return (long) VarInt.getLength(bytes.length) + bytes.length; + } + + public static long sizeOfDecimal(BigDecimal bd) { + int magBytes = (bd.unscaledValue().bitLength() >>> 3) + 1; + return (long) VarInt.getLength(bd.scale()) + VarInt.getLength(magBytes) + magBytes; + } + + public static long sizeOfLocalDate(LocalDate d) { + return VarInt.getLength(d.toEpochDay()); + } + + public static long sizeOfLocalTime(LocalTime t) { + return VarInt.getLength(t.toNanoOfDay()); + } + + public static long sizeOfLocalDateTime(LocalDateTime dt) { + return 2L + + VarInt.getLength(dt.toLocalDate().toEpochDay()) + + VarInt.getLength(dt.toLocalTime().toNanoOfDay()); + } + + public static long sizeOfUuid(UUID u) { + return 2L + + VarInt.getLength(u.getMostSignificantBits()) + + VarInt.getLength(u.getLeastSignificantBits()); + } + + public static long sizeOfNanosInstant(java.time.Instant i) { + return 2L + VarInt.getLength(i.getEpochSecond()) + VarInt.getLength(i.getNano()); + } + + public static long sizeOfMicrosInstant(java.time.Instant i) { + return 2L + VarInt.getLength(i.getEpochSecond()) + VarInt.getLength(i.getNano() / 1000); + } + + public static long sizeOfNanosDuration(Duration d) { + return 2L + VarInt.getLength(d.getSeconds()) + VarInt.getLength(d.getNano()); + } + + public static long sizeOfTimestamp(java.time.Instant i, int precision) { + long secBytes = VarInt.getLength(i.getEpochSecond()); + if (precision < 5) { + return 4L + secBytes; + } + int scalingFactor = TIMESTAMP_SCALING_FACTORS[precision]; + int subseconds = scalingFactor == 1 ? i.getNano() : i.getNano() / scalingFactor; + return 2L + secBytes + VarInt.getLength(subseconds); + } + + public static long sizeOfStringCollection(Collection col) throws CoderException { + long total = 4L; + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0, n = list.size(); i < n; i++) { + String s = list.get(i); + if (s == null) { + throw new CoderException("cannot encode a null String"); + } + total += sizeOfString(s); + } + } else { + for (String s : col) { + if (s == null) { + throw new CoderException("cannot encode a null String"); + } + total += sizeOfString(s); + } + } + return total; + } + + public static long sizeOfInt32Collection(Collection col) throws CoderException { + long total = 4L; + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0, n = list.size(); i < n; i++) { + Integer v = list.get(i); + if (v == null) { + throw new CoderException("cannot encode a null Integer"); + } + total += VarInt.getLength(v.intValue()); + } + } else { + for (Integer v : col) { + if (v == null) { + throw new CoderException("cannot encode a null Integer"); + } + total += VarInt.getLength(v.intValue()); + } + } + return total; + } + + public static long sizeOfInt64Collection(Collection col) throws CoderException { + long total = 4L; + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0, n = list.size(); i < n; i++) { + Long v = list.get(i); + if (v == null) { + throw new CoderException("cannot encode a null Long"); + } + total += VarInt.getLength(v.longValue()); + } + } else { + for (Long v : col) { + if (v == null) { + throw new CoderException("cannot encode a null Long"); + } + total += VarInt.getLength(v.longValue()); + } + } + return total; + } + + public static long sizeOfDoubleCollection(Collection col) throws CoderException { + int size = col.size(); + if (col instanceof List && col instanceof RandomAccess) { + List list = (List) col; + for (int i = 0; i < size; i++) { + if (list.get(i) == null) { + throw new CoderException("cannot encode a null Double"); + } + } + } else { + for (Double v : col) { + if (v == null) { + throw new CoderException("cannot encode a null Double"); + } + } + } + return 4L + ((long) size << 3); + } + + public static long sizeOfStringLongMap(Map map) throws CoderException { + long total = 4L; + for (Map.Entry e : map.entrySet()) { + String k = e.getKey(); + Long v = e.getValue(); + if (k == null) { + throw new CoderException("cannot encode a null String"); + } + if (v == null) { + throw new CoderException("cannot encode a null Long"); + } + total += sizeOfString(k) + VarInt.getLength(v.longValue()); + } + return total; + } + + public static long sizeOfStringStringMap(Map map) throws CoderException { + long total = 4L; + for (Map.Entry e : map.entrySet()) { + String k = e.getKey(); + String v = e.getValue(); + if (k == null || v == null) { + throw new CoderException("cannot encode a null String"); + } + total += sizeOfString(k) + sizeOfString(v); + } + return total; + } + + public static long sizeOfStringIntMap(Map map) throws CoderException { + long total = 4L; + for (Map.Entry e : map.entrySet()) { + String k = e.getKey(); + Integer v = e.getValue(); + if (k == null) { + throw new CoderException("cannot encode a null String"); + } + if (v == null) { + throw new CoderException("cannot encode a null Integer"); + } + total += sizeOfString(k) + VarInt.getLength(v.intValue()); + } + return total; + } + + public static long sizeOfStringDoubleMap(Map map) throws CoderException { + long total = 4L; + for (Map.Entry e : map.entrySet()) { + String k = e.getKey(); + Double v = e.getValue(); + if (k == null) { + throw new CoderException("cannot encode a null String"); + } + if (v == null) { + throw new CoderException("cannot encode a null Double"); + } + total += sizeOfString(k) + 8L; + } + return total; + } + + public static long sizeOfNullMask(int highestNullPos) { + if (highestNullPos < 0) { + return 1L; + } + int numBytes = (highestNullPos >>> 3) + 1; + return (long) VarInt.getLength(numBytes) + numBytes; + } +} diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java index 5223cab8f7ca..931a5cd62c7e 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java @@ -33,6 +33,7 @@ import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.util.SerializableUtils; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptor; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; @@ -47,7 +48,7 @@ public class SchemaCoder extends CustomCoder { private final TypeDescriptor typeDescriptor; private final SerializableFunction toRowFunction; private final SerializableFunction fromRowFunction; - private transient @Nullable Coder delegateCoder; + private transient volatile @Nullable Coder delegateCoder; protected SchemaCoder( Schema schema, @@ -108,12 +109,14 @@ public SerializableFunction getToRowFunction() { } private Coder getDelegateCoder() { - if (delegateCoder == null) { + Coder coder = delegateCoder; + if (coder == null) { // RowCoderGenerator caches based on id, so if a new instance of this RowCoder is // deserialized, we don't need to run ByteBuddy again to construct the class. - delegateCoder = RowCoderGenerator.generate(schema); + coder = RowCoderGenerator.generate(schema); + delegateCoder = coder; } - return delegateCoder; + return coder; } @Override @@ -126,6 +129,19 @@ public T decode(InputStream inStream) throws IOException { return fromRowFunction.apply(getDelegateCoder().decode(inStream)); } + @Override + public boolean isRegisterByteSizeObserverCheap(T value) { + if (value == null) { + return false; + } + return getDelegateCoder().isRegisterByteSizeObserverCheap(toRowFunction.apply(value)); + } + + @Override + public void registerByteSizeObserver(T value, ElementByteSizeObserver observer) throws Exception { + getDelegateCoder().registerByteSizeObserver(toRowFunction.apply(value), observer); + } + @Override public void verifyDeterministic() throws org.apache.beam.sdk.coders.Coder.NonDeterministicException { diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoderHelpers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoderHelpers.java index dfc0d82d2145..f8ee2aee3c2f 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoderHelpers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoderHelpers.java @@ -20,9 +20,16 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.UUID; import org.apache.beam.sdk.coders.BigDecimalCoder; import org.apache.beam.sdk.coders.BigEndianShortCoder; import org.apache.beam.sdk.coders.BooleanCoder; @@ -30,6 +37,7 @@ import org.apache.beam.sdk.coders.ByteCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.CoderException; +import org.apache.beam.sdk.coders.CustomCoder; import org.apache.beam.sdk.coders.DoubleCoder; import org.apache.beam.sdk.coders.FloatCoder; import org.apache.beam.sdk.coders.InstantCoder; @@ -37,15 +45,29 @@ import org.apache.beam.sdk.coders.ListCoder; import org.apache.beam.sdk.coders.MapCoder; import org.apache.beam.sdk.coders.NullableCoder; +import org.apache.beam.sdk.coders.RowCoderGenerator; +import org.apache.beam.sdk.coders.RowWireCodec; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.coders.VarIntCoder; import org.apache.beam.sdk.coders.VarLongCoder; import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.schemas.Schema.LogicalType; import org.apache.beam.sdk.schemas.Schema.TypeName; +import org.apache.beam.sdk.schemas.logicaltypes.Date; +import org.apache.beam.sdk.schemas.logicaltypes.DateTime; +import org.apache.beam.sdk.schemas.logicaltypes.EnumerationType; +import org.apache.beam.sdk.schemas.logicaltypes.MicrosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.NanosDuration; +import org.apache.beam.sdk.schemas.logicaltypes.NanosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.PassThroughLogicalType; +import org.apache.beam.sdk.schemas.logicaltypes.Time; +import org.apache.beam.sdk.schemas.logicaltypes.Timestamp; +import org.apache.beam.sdk.schemas.logicaltypes.UuidLogicalType; +import org.apache.beam.sdk.util.VarInt; import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; +import org.checkerframework.checker.nullness.qual.Nullable; import org.joda.time.ReadableInstant; @SuppressWarnings({ @@ -69,15 +91,340 @@ class SchemaCoderHelpers { .put(TypeName.BOOLEAN, BooleanCoder.of()) .build(); + private static boolean canUseDirectRowEncoding(Schema rowSchema) { + return !rowSchema.isEncodingPositionsOverridden() + && !rowSchema.isStaticEncoding() + && !RowCoderGenerator.hasEncodingPositionOverride(rowSchema.getUUID()); + } + + private static boolean isBaseTypeAlwaysCheap(FieldType baseType) { + switch (baseType.getTypeName()) { + case BYTE: + case INT16: + case INT32: + case INT64: + case FLOAT: + case DOUBLE: + case BOOLEAN: + case DATETIME: + case BYTES: + case DECIMAL: + return true; + default: + return false; + } + } + + private static boolean isIdentityPassThrough(LogicalType logicalType) { + if (!(logicalType instanceof PassThroughLogicalType)) { + return false; + } + // Preserve ReadableInstant -> Instant coercion handled inside LogicalTypeCoder. + if (logicalType.getBaseType().getTypeName() == TypeName.DATETIME) { + return false; + } + Class clazz = logicalType.getClass(); + try { + return clazz.getMethod("toBaseType", Object.class).getDeclaringClass() + == PassThroughLogicalType.class + && clazz.getMethod("toInputType", Object.class).getDeclaringClass() + == PassThroughLogicalType.class; + } catch (NoSuchMethodException | SecurityException e) { + return false; + } + } + + /** Shared base for zero-Row-allocation specialized logical-type coders. */ + private abstract static class DirectLogicalTypeCoder extends CustomCoder { + @Override + public void verifyDeterministic() {} + + @Override + public boolean consistentWithEquals() { + return true; + } + + @Override + public boolean isRegisterByteSizeObserverCheap(T value) { + return true; + } + + @Override + public void registerByteSizeObserver(T value, ElementByteSizeObserver observer) + throws Exception { + observer.update(getEncodedElementByteSize(value)); + } + + @Override + @SuppressWarnings("EqualsGetClass") + public boolean equals(@Nullable Object o) { + return o != null && getClass() == o.getClass(); + } + + @Override + public int hashCode() { + return getClass().hashCode(); + } + } + + /** Direct zero-Row-alloc coder for {@link Date} matching {@code VarLongCoder} bytes. */ + private static final class DateLogicalTypeCoder extends DirectLogicalTypeCoder { + static final DateLogicalTypeCoder INSTANCE = new DateLogicalTypeCoder(); + + @Override + public void encode(LocalDate value, OutputStream outStream) throws IOException { + RowWireCodec.writeLocalDate(value, outStream); + } + + @Override + public LocalDate decode(InputStream inStream) throws IOException { + return RowWireCodec.readLocalDate(inStream); + } + + @Override + protected long getEncodedElementByteSize(LocalDate value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null LocalDate"); + } + return RowWireCodec.sizeOfLocalDate(value); + } + } + + /** Direct zero-Row-alloc coder for {@link Time} matching {@code VarLongCoder} bytes. */ + private static final class TimeLogicalTypeCoder extends DirectLogicalTypeCoder { + static final TimeLogicalTypeCoder INSTANCE = new TimeLogicalTypeCoder(); + + @Override + public void encode(LocalTime value, OutputStream outStream) throws IOException { + RowWireCodec.writeLocalTime(value, outStream); + } + + @Override + public LocalTime decode(InputStream inStream) throws IOException { + return RowWireCodec.readLocalTime(inStream); + } + + @Override + protected long getEncodedElementByteSize(LocalTime value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null LocalTime"); + } + return RowWireCodec.sizeOfLocalTime(value); + } + } + + /** Direct zero-Row-alloc coder for {@link DateTime} matching {@code beam:coder:row:v1}. */ + private static final class DateTimeLogicalTypeCoder + extends DirectLogicalTypeCoder { + static final DateTimeLogicalTypeCoder INSTANCE = new DateTimeLogicalTypeCoder(); + + @Override + public void encode(LocalDateTime value, OutputStream outStream) throws IOException { + RowWireCodec.writeLocalDateTime(value, outStream); + } + + @Override + public LocalDateTime decode(InputStream inStream) throws IOException { + return RowWireCodec.readLocalDateTime(inStream); + } + + @Override + protected long getEncodedElementByteSize(LocalDateTime value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null LocalDateTime"); + } + return RowWireCodec.sizeOfLocalDateTime(value); + } + } + + /** Direct zero-Row-alloc coder for {@link UuidLogicalType} matching {@code beam:coder:row:v1}. */ + private static final class UuidLogicalTypeCoder extends DirectLogicalTypeCoder { + static final UuidLogicalTypeCoder INSTANCE = new UuidLogicalTypeCoder(); + + @Override + public void encode(UUID value, OutputStream outStream) throws IOException { + RowWireCodec.writeUuid(value, outStream); + } + + @Override + public UUID decode(InputStream inStream) throws IOException { + return RowWireCodec.readUuid(inStream); + } + + @Override + protected long getEncodedElementByteSize(UUID value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null UUID"); + } + return RowWireCodec.sizeOfUuid(value); + } + } + + /** Direct zero-Row-alloc coder for {@link Timestamp} matching {@code beam:coder:row:v1}. */ + private static final class TimestampLogicalTypeCoder extends DirectLogicalTypeCoder { + private final int precision; + + TimestampLogicalTypeCoder(int precision) { + this.precision = precision; + } + + @Override + public void encode(Instant value, OutputStream outStream) throws IOException { + RowWireCodec.writeTimestamp(value, precision, outStream); + } + + @Override + public Instant decode(InputStream inStream) throws IOException { + return RowWireCodec.readTimestamp(precision, inStream); + } + + @Override + protected long getEncodedElementByteSize(Instant value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null Instant"); + } + return RowWireCodec.sizeOfTimestamp(value, precision); + } + + @Override + @SuppressWarnings("EqualsGetClass") + public boolean equals(@Nullable Object o) { + return o instanceof TimestampLogicalTypeCoder + && precision == ((TimestampLogicalTypeCoder) o).precision; + } + + @Override + public int hashCode() { + return 31 * TimestampLogicalTypeCoder.class.hashCode() + precision; + } + } + + /** Direct zero-Row-alloc coder for {@link MicrosInstant} matching {@code beam:coder:row:v1}. */ + private static final class MicrosInstantLogicalTypeCoder extends DirectLogicalTypeCoder { + static final MicrosInstantLogicalTypeCoder INSTANCE = new MicrosInstantLogicalTypeCoder(); + + @Override + public void encode(Instant value, OutputStream outStream) throws IOException { + RowWireCodec.writeMicrosInstant(value, outStream); + } + + @Override + public Instant decode(InputStream inStream) throws IOException { + return RowWireCodec.readMicrosInstant(inStream); + } + + @Override + protected long getEncodedElementByteSize(Instant value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null Instant"); + } + return RowWireCodec.sizeOfMicrosInstant(value); + } + } + + /** Direct zero-Row-alloc coder for {@link NanosInstant} matching {@code beam:coder:row:v1}. */ + private static final class NanosInstantLogicalTypeCoder extends DirectLogicalTypeCoder { + static final NanosInstantLogicalTypeCoder INSTANCE = new NanosInstantLogicalTypeCoder(); + + @Override + public void encode(Instant value, OutputStream outStream) throws IOException { + RowWireCodec.writeNanosInstant(value, outStream); + } + + @Override + public Instant decode(InputStream inStream) throws IOException { + return RowWireCodec.readNanosInstant(inStream); + } + + @Override + protected long getEncodedElementByteSize(Instant value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null Instant"); + } + return RowWireCodec.sizeOfNanosInstant(value); + } + } + + /** Direct zero-Row-alloc coder for {@link NanosDuration} matching {@code beam:coder:row:v1}. */ + private static final class NanosDurationLogicalTypeCoder + extends DirectLogicalTypeCoder { + static final NanosDurationLogicalTypeCoder INSTANCE = new NanosDurationLogicalTypeCoder(); + + @Override + public void encode(Duration value, OutputStream outStream) throws IOException { + RowWireCodec.writeNanosDuration(value, outStream); + } + + @Override + public Duration decode(InputStream inStream) throws IOException { + return RowWireCodec.readNanosDuration(inStream); + } + + @Override + protected long getEncodedElementByteSize(Duration value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null Duration"); + } + return RowWireCodec.sizeOfNanosDuration(value); + } + } + + /** Direct non-boxing coder for {@link EnumerationType} returning cached {@code Value}s. */ + private static final class EnumerationLogicalTypeCoder + extends DirectLogicalTypeCoder { + private final EnumerationType enumType; + + EnumerationLogicalTypeCoder(EnumerationType enumType) { + this.enumType = enumType; + } + + @Override + public void encode(EnumerationType.Value value, OutputStream outStream) throws IOException { + if (value == null) { + throw new CoderException("cannot encode a null EnumerationType.Value"); + } + RowWireCodec.writeVarInt(value.getValue(), outStream); + } + + @Override + public EnumerationType.Value decode(InputStream inStream) throws IOException { + return enumType.valueOf(RowWireCodec.readVarInt(inStream)); + } + + @Override + protected long getEncodedElementByteSize(EnumerationType.Value value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null EnumerationType.Value"); + } + return VarInt.getLength(value.getValue()); + } + + @Override + @SuppressWarnings("EqualsGetClass") + public boolean equals(@Nullable Object o) { + return o instanceof EnumerationLogicalTypeCoder + && Objects.equals( + enumType.getValuesMap(), ((EnumerationLogicalTypeCoder) o).enumType.getValuesMap()); + } + + @Override + public int hashCode() { + return enumType.getValuesMap().hashCode(); + } + } + private static class LogicalTypeCoder extends Coder { private final LogicalType logicalType; private final Coder baseTypeCoder; private final boolean isDateTime; + private final boolean baseTypeAlwaysCheap; LogicalTypeCoder(LogicalType logicalType, Coder baseTypeCoder) { this.logicalType = logicalType; this.baseTypeCoder = baseTypeCoder; - this.isDateTime = logicalType.getBaseType().equals(FieldType.DATETIME); + FieldType baseType = logicalType.getBaseType(); + this.isDateTime = baseType.getTypeName() == TypeName.DATETIME; + this.baseTypeAlwaysCheap = isBaseTypeAlwaysCheap(baseType); } @Override @@ -123,14 +470,76 @@ public Object structuralValue(InputT value) { @Override public boolean isRegisterByteSizeObserverCheap(InputT value) { - return baseTypeCoder.isRegisterByteSizeObserverCheap(logicalType.toBaseType(value)); + if (baseTypeAlwaysCheap) { + return true; + } + BaseT base = logicalType.toBaseType(value); + if (isDateTime) { + base = (BaseT) ((ReadableInstant) base).toInstant(); + } + return baseTypeCoder.isRegisterByteSizeObserverCheap(base); } @Override public void registerByteSizeObserver(InputT value, ElementByteSizeObserver observer) throws Exception { - baseTypeCoder.registerByteSizeObserver(logicalType.toBaseType(value), observer); + BaseT base = logicalType.toBaseType(value); + if (isDateTime) { + base = (BaseT) ((ReadableInstant) base).toInstant(); + } + baseTypeCoder.registerByteSizeObserver(base, observer); + } + } + + private static Coder coderForLogicalType(LogicalType logicalType) { + Class clazz = logicalType.getClass(); + if (clazz == Date.class) { + return DateLogicalTypeCoder.INSTANCE; + } + if (clazz == Time.class) { + return TimeLogicalTypeCoder.INSTANCE; + } + if (clazz == DateTime.class && canUseDirectRowEncoding(DateTime.DATETIME_SCHEMA)) { + return DateTimeLogicalTypeCoder.INSTANCE; + } + if (clazz == UuidLogicalType.class && canUseDirectRowEncoding(UuidLogicalType.UUID_SCHEMA)) { + return UuidLogicalTypeCoder.INSTANCE; } + if (clazz == Timestamp.class) { + Schema baseSchema = logicalType.getBaseType().getRowSchema(); + if (baseSchema != null && canUseDirectRowEncoding(baseSchema)) { + Integer precision = ((Timestamp) logicalType).getArgument(); + if (precision != null && precision >= 0 && precision <= 9) { + return new TimestampLogicalTypeCoder(precision); + } + } + } + if (clazz == MicrosInstant.class) { + Schema baseSchema = logicalType.getBaseType().getRowSchema(); + if (baseSchema != null && canUseDirectRowEncoding(baseSchema)) { + return MicrosInstantLogicalTypeCoder.INSTANCE; + } + } + if (clazz == NanosInstant.class) { + Schema baseSchema = logicalType.getBaseType().getRowSchema(); + if (baseSchema != null && canUseDirectRowEncoding(baseSchema)) { + return NanosInstantLogicalTypeCoder.INSTANCE; + } + } + if (clazz == NanosDuration.class) { + Schema baseSchema = logicalType.getBaseType().getRowSchema(); + if (baseSchema != null && canUseDirectRowEncoding(baseSchema)) { + return NanosDurationLogicalTypeCoder.INSTANCE; + } + } + if (clazz == EnumerationType.class) { + return new EnumerationLogicalTypeCoder((EnumerationType) logicalType); + } + Coder baseTypeCoder = coderForFieldType(logicalType.getBaseType()); + if (isIdentityPassThrough(logicalType)) { + return baseTypeCoder; + } + return new LogicalTypeCoder(logicalType, baseTypeCoder); } /** Returns the coder used for a given primitive type. */ @@ -155,10 +564,7 @@ public static Coder coderForFieldType(FieldType fieldType) { coderForFieldType(fieldType.getMapValueType())); break; case LOGICAL_TYPE: - coder = - new LogicalTypeCoder( - fieldType.getLogicalType(), - coderForFieldType(fieldType.getLogicalType().getBaseType())); + coder = (Coder) coderForLogicalType(fieldType.getLogicalType()); break; default: coder = (Coder) CODER_MAP.get(fieldType.getTypeName()); From 428d704c00f4cf57aa343bc3f2a488d8be709c10 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:54:38 -0800 Subject: [PATCH 05/15] Add DirectSchemaCoderGenerator for fused POJO and JavaBean coding Generates fused ByteBuddy Coder implementations for accessible POJO and JavaBean types that read/write unboxed fields, getters, and setters directly against RowWireCodec without RowWithGetters, RowWithStorage, Object[], or FromRowUsingCreator overhead: - Supports 1..64-field single-method unrolled codecs and 65..512-field 32-field chunked codecs (with single-buffer in-place wide null header packing, evaluate-once RefScratchPool for wide nullable JavaBeans, bit-packed zero-alloc chunked byte-size observation, OOM-safe try/catch pool scopes, and automatic schema-evolution fallback). - Wires direct-coder dispatch into SchemaCoder (falling back transparently for >512 fields or inaccessible/unsupported types). - Adds comprehensive DirectSchemaCoderTest covering unrolled and chunked POJO/JavaBean/RowCoder paths, exact cutoffs (64/65/1024/1025/4200), reversed encodingPositions, evolution, error branches, RowWireCodec edge cases, POJOUtils chunked creators, and Schema compact caching. --- .../schemas/DirectSchemaCoderGenerator.java | 4089 +++++++++++++++ .../apache/beam/sdk/schemas/SchemaCoder.java | 66 +- .../sdk/schemas/DirectSchemaCoderTest.java | 4379 +++++++++++++++++ 3 files changed, 8533 insertions(+), 1 deletion(-) create mode 100644 sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/DirectSchemaCoderGenerator.java create mode 100644 sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/DirectSchemaCoderTest.java diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/DirectSchemaCoderGenerator.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/DirectSchemaCoderGenerator.java new file mode 100644 index 000000000000..1a02a414da7c --- /dev/null +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/DirectSchemaCoderGenerator.java @@ -0,0 +1,4089 @@ +/* + * 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.beam.sdk.schemas; + +import static org.apache.beam.sdk.util.ByteBuddyUtils.getClassLoadingStrategy; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.asm.AsmVisitorWrapper; +import net.bytebuddy.description.modifier.Visibility; +import net.bytebuddy.dynamic.ClassFileLocator; +import net.bytebuddy.dynamic.DynamicType; +import net.bytebuddy.dynamic.scaffold.InstrumentedType; +import net.bytebuddy.implementation.Implementation; +import net.bytebuddy.implementation.bytecode.ByteCodeAppender; +import net.bytebuddy.jar.asm.ClassWriter; +import net.bytebuddy.jar.asm.Label; +import net.bytebuddy.jar.asm.MethodVisitor; +import net.bytebuddy.jar.asm.Opcodes; +import net.bytebuddy.jar.asm.Type; +import net.bytebuddy.matcher.ElementMatchers; +import net.bytebuddy.pool.TypePool; +import org.apache.beam.sdk.annotations.Internal; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.CoderException; +import org.apache.beam.sdk.coders.CustomCoder; +import org.apache.beam.sdk.coders.DoubleCoder; +import org.apache.beam.sdk.coders.IterableCoder; +import org.apache.beam.sdk.coders.RowCoderGenerator; +import org.apache.beam.sdk.coders.RowWireCodec; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.coders.VarLongCoder; +import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.Schema.LogicalType; +import org.apache.beam.sdk.schemas.Schema.TypeName; +import org.apache.beam.sdk.schemas.logicaltypes.Date; +import org.apache.beam.sdk.schemas.logicaltypes.DateTime; +import org.apache.beam.sdk.schemas.logicaltypes.EnumerationType; +import org.apache.beam.sdk.schemas.logicaltypes.MicrosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.NanosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.Time; +import org.apache.beam.sdk.schemas.logicaltypes.UuidLogicalType; +import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils; +import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.InjectPackageStrategy; +import org.apache.beam.sdk.schemas.utils.ReflectUtils; +import org.apache.beam.sdk.transforms.SerializableFunction; +import org.apache.beam.sdk.util.VarInt; +import org.apache.beam.sdk.util.common.ElementByteSizeObservableIterable; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; +import org.apache.beam.sdk.util.common.ReflectHelpers; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.TypeDescriptor; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Generates fused ByteBuddy {@link Coder} implementations for {@link JavaFieldSchema} POJOs and + * {@link JavaBeanSchema} JavaBeans that bypass intermediate {@link Row} allocation, primitive + * boxing, and logical-type round-trips while emitting the exact {@code beam:coder:row:v1} wire + * format. + * + *

For schemas with {@code 1 <= fieldCount <= 64}, emits straight-line single-method encode, + * decode, and byte-size implementations. For wider schemas ({@code 65 <= fieldCount <= 512}), emits + * chunked 32-field private helper methods on the same generated coder class so every method stays + * well below HotSpot C2's 8KB {@code HugeMethodLimit} while still bypassing intermediate {@link + * Row} allocations. On any unsupported type, annotation, access restriction, or schema count above + * {@code 512}, {@link #tryGenerate} returns {@code null} and {@link SchemaCoder} falls back cleanly + * to {@code RowCoderGenerator}. On schema evolution ({@code streamFieldCount != fieldCount}, or an + * oversized null bitmap on the {@code <= 64} single-method path), the generated coder delegates the + * remainder of the stream to {@link RowCoderGenerator#decodeAfterFieldCount} or {@link + * RowCoderGenerator#decodeAfterNullByteLen}; chunked wide decoders handle arbitrary {@code + * nullByteLen} directly via {@link RowWireCodec#readNullBytes}. + */ +@Internal +@SuppressWarnings({"nullness", "rawtypes"}) +public final class DirectSchemaCoderGenerator { + private static final Logger LOG = LoggerFactory.getLogger(DirectSchemaCoderGenerator.class); + private static final int MAX_DIRECT_FIELDS = 64; + // Chunked wide encode patches a 1-byte nullByteLen prefix directly in the 512-byte ScratchPool + // buffer, which requires ceil(MAX_CHUNKED_DIRECT_FIELDS / 8) <= 127 (i.e. <= 1016 fields). + private static final int MAX_CHUNKED_DIRECT_FIELDS = 512; + private static final int DIRECT_CHUNK_SIZE = 32; + private static final int MAX_CLASSES_PER_TYPE = 32; + + static { + if (((MAX_CHUNKED_DIRECT_FIELDS + 7) >>> 3) > 127) { + throw new AssertionError( + "MAX_CHUNKED_DIRECT_FIELDS exceeds 1-byte nullByteLen in-place header limit"); + } + } + + private static final String WIRE_CODEC = "org/apache/beam/sdk/coders/RowWireCodec"; + private static final String SCRATCH_POOL = "org/apache/beam/sdk/coders/RowWireCodec$ScratchPool"; + private static final String SCRATCH_POOL_DESC = + "Lorg/apache/beam/sdk/coders/RowWireCodec$ScratchPool;"; + private static final String REF_SCRATCH_POOL = + "org/apache/beam/sdk/coders/RowWireCodec$RefScratchPool"; + private static final String REF_SCRATCH_POOL_DESC = + "Lorg/apache/beam/sdk/coders/RowWireCodec$RefScratchPool;"; + private static final String BASE_TYPE = Type.getInternalName(DirectSchemaCoderBase.class); + private static final String GEN_TYPE = Type.getInternalName(DirectSchemaCoderGenerator.class); + private static final String CODER_TYPE = "org/apache/beam/sdk/coders/Coder"; + private static final String OBSERVER_TYPE = + "org/apache/beam/sdk/util/common/ElementByteSizeObserver"; + private static final String OBSERVABLE_ITERABLE_TYPE = + "org/apache/beam/sdk/util/common/ElementByteSizeObservableIterable"; + private static final String VARINT_TYPE = "org/apache/beam/sdk/util/VarInt"; + private static final String OUT_DESC = "Ljava/io/OutputStream;"; + private static final String IN_DESC = "Ljava/io/InputStream;"; + private static final String OBSERVER_DESC = + "Lorg/apache/beam/sdk/util/common/ElementByteSizeObserver;"; + + private static final ByteBuddy BYTE_BUDDY = new ByteBuddy(); + + // Anchor generated coder classes to targetClass via ClassValue so user ClassLoaders (e.g. + // Spark/Flink job classloaders) are never pinned by static maps and can unload cleanly. + private static final ClassValue< + ConcurrentHashMap>> + CLASS_CACHE = + new ClassValue< + ConcurrentHashMap>>() { + @Override + protected ConcurrentHashMap> + computeValue(Class type) { + return new ConcurrentHashMap<>(); + } + }; + + private static final IterableCoder LAZY_STRING_ITERABLE_CODER = + IterableCoder.of(StringUtf8Coder.of()); + private static final IterableCoder LAZY_INT32_ITERABLE_CODER = + IterableCoder.of(VarIntCoder.of()); + private static final IterableCoder LAZY_INT64_ITERABLE_CODER = + IterableCoder.of(VarLongCoder.of()); + private static final IterableCoder LAZY_DOUBLE_ITERABLE_CODER = + IterableCoder.of(DoubleCoder.of()); + + private DirectSchemaCoderGenerator() {} + + /** Shared base class for generated fused POJO/JavaBean coders. */ + @Internal + public abstract static class DirectSchemaCoderBase extends CustomCoder { + protected final Schema schema; + protected final SerializableFunction fromRowFunction; + protected final Coder[] subCoders; + // Lazily generated only if schema-evolution decode or verifyDeterministic is actually invoked. + private transient volatile @Nullable Coder fallbackRowCoder; + + protected DirectSchemaCoderBase( + Schema schema, SerializableFunction fromRowFunction, Coder[] subCoders) { + this.schema = schema; + this.fromRowFunction = fromRowFunction; + this.subCoders = subCoders; + } + + protected final Coder getFallbackRowCoder() { + Coder coder = fallbackRowCoder; + if (coder == null) { + coder = RowCoderGenerator.generate(schema); + fallbackRowCoder = coder; + } + return coder; + } + + @Override + public void verifyDeterministic() throws NonDeterministicException { + getFallbackRowCoder().verifyDeterministic(); + } + + protected final T decodeEvolved(int streamFieldCount, InputStream in) throws IOException { + Row row = + RowCoderGenerator.decodeAfterFieldCount(getFallbackRowCoder(), streamFieldCount, in); + return fromRowFunction.apply(row); + } + + protected final T decodeEvolvedAfterNullLen( + int streamFieldCount, int nullByteLen, InputStream in) throws IOException { + Row row = + RowCoderGenerator.decodeAfterNullByteLen( + getFallbackRowCoder(), streamFieldCount, nullByteLen, in); + return fromRowFunction.apply(row); + } + + protected static IOException invalidNullBitmapLength(int nullByteLen) { + return new CoderException("Invalid null bitset length: " + nullByteLen); + } + + protected static IOException cannotEncodeNull(String className) { + return new CoderException("cannot encode a null " + className); + } + + protected static NullPointerException nullPrimitive(String fieldName) { + return new NullPointerException("Cannot decode null into primitive field " + fieldName); + } + } + + /** Bounds-checked enum lookup by ordinal backed by cached {@link ClassValue}. */ + @Internal + public static Object enumConstantForOrdinal(Class enumClass, int ordinal) { + return ByteBuddyUtils.enumConstantForOrdinal(enumClass, ordinal); + } + + /** Observes byte size for {@code Collection}, delegating lazily if observable. */ + @Internal + public static long observeStringCollectionByteSize( + Collection col, ElementByteSizeObserver observer) throws Exception { + if (col instanceof ElementByteSizeObservableIterable) { + LAZY_STRING_ITERABLE_CODER.registerByteSizeObserver(col, observer); + return 0L; + } + return RowWireCodec.sizeOfStringCollection(col); + } + + /** Observes byte size for {@code Collection}, delegating lazily if observable. */ + @Internal + public static long observeInt32CollectionByteSize( + Collection col, ElementByteSizeObserver observer) throws Exception { + if (col instanceof ElementByteSizeObservableIterable) { + LAZY_INT32_ITERABLE_CODER.registerByteSizeObserver(col, observer); + return 0L; + } + return RowWireCodec.sizeOfInt32Collection(col); + } + + /** Observes byte size for {@code Collection}, delegating lazily if observable. */ + @Internal + public static long observeInt64CollectionByteSize( + Collection col, ElementByteSizeObserver observer) throws Exception { + if (col instanceof ElementByteSizeObservableIterable) { + LAZY_INT64_ITERABLE_CODER.registerByteSizeObserver(col, observer); + return 0L; + } + return RowWireCodec.sizeOfInt64Collection(col); + } + + /** Observes byte size for {@code Collection}, delegating lazily if observable. */ + @Internal + public static long observeDoubleCollectionByteSize( + Collection col, ElementByteSizeObserver observer) throws Exception { + if (col instanceof ElementByteSizeObservableIterable) { + LAZY_DOUBLE_ITERABLE_CODER.registerByteSizeObserver(col, observer); + return 0L; + } + return RowWireCodec.sizeOfDoubleCollection(col); + } + + /** + * Observes byte size for {@code Collection} with a nested direct coder, delegating lazily + * via {@link IterableCoder} if the collection implements {@link + * ElementByteSizeObservableIterable}. + */ + @Internal + @SuppressWarnings("unchecked") + public static void observeElementCollectionByteSize( + Collection col, Coder elemCoder, ElementByteSizeObserver observer) throws Exception { + if (col instanceof ElementByteSizeObservableIterable) { + IterableCoder.of(elemCoder).registerByteSizeObserver(col, observer); + return; + } + observer.update(4L); + if (col instanceof List && col instanceof java.util.RandomAccess) { + List list = (List) col; + for (int i = 0, n = list.size(); i < n; i++) { + elemCoder.registerByteSizeObserver(list.get(i), observer); + } + } else { + for (Object elem : col) { + elemCoder.registerByteSizeObserver(elem, observer); + } + } + } + + /** + * Reads a Joda {@link org.joda.time.DateTime} using the exact {@code beam:coder:row:v1} wire + * format. + */ + @Internal + public static org.joda.time.DateTime readJodaDateTime(InputStream in, byte[] buf) + throws IOException { + return new org.joda.time.DateTime(RowWireCodec.readBigEndianLong(in, buf) + Long.MIN_VALUE); + } + + private enum FieldKind { + PRIM_BYTE, + PRIM_SHORT, + PRIM_INT, + PRIM_LONG, + PRIM_FLOAT, + PRIM_DOUBLE, + PRIM_BOOL, + BOX_BYTE, + BOX_SHORT, + BOX_INT, + BOX_LONG, + BOX_FLOAT, + BOX_DOUBLE, + BOX_BOOL, + STRING, + BYTES, + DECIMAL, + JODA_INSTANT, + JODA_DATETIME, + LOCAL_DATE, + LOCAL_TIME, + LOCAL_DATETIME, + UUID_TYPE, + NANOS_INSTANT, + MICROS_INSTANT, + ENUM_ORDINAL, + LIST_STRING, + LIST_INT, + LIST_LONG, + LIST_DOUBLE, + LIST_ROW, + MAP_STRING_LONG, + MAP_STRING_STRING, + MAP_STRING_INT, + MAP_STRING_DOUBLE, + SUB_ROW; + + boolean isPrimitive() { + return this == PRIM_BYTE + || this == PRIM_SHORT + || this == PRIM_INT + || this == PRIM_LONG + || this == PRIM_FLOAT + || this == PRIM_DOUBLE + || this == PRIM_BOOL; + } + } + + private static final class FieldSpec { + final int rowIndex; + final int encPos; + final String schemaFieldName; + final boolean nullable; + final FieldKind kind; + final Class javaType; + final @Nullable Field pojoField; + final @Nullable Method getter; + final @Nullable Method setter; + final @Nullable Coder subCoder; + + FieldSpec( + int rowIndex, + int encPos, + String schemaFieldName, + boolean nullable, + FieldKind kind, + Class javaType, + @Nullable Field pojoField, + @Nullable Method getter, + @Nullable Method setter, + @Nullable Coder subCoder) { + this.rowIndex = rowIndex; + this.encPos = encPos; + this.schemaFieldName = schemaFieldName; + this.nullable = nullable; + this.kind = kind; + this.javaType = javaType; + this.pojoField = pojoField; + this.getter = getter; + this.setter = setter; + this.subCoder = subCoder; + } + + boolean isPojo() { + return pojoField != null; + } + } + + private static final class CoderClassKey { + final Class targetClass; + final Class providerClass; + final Schema schema; + final int[] encodingPosToIndex; + final boolean staticEncoding; + final int hash; + + CoderClassKey( + Class targetClass, + Class providerClass, + Schema schema, + int[] encodingPosToIndex, + boolean staticEncoding) { + this.targetClass = targetClass; + this.providerClass = providerClass; + this.schema = schema; + this.encodingPosToIndex = encodingPosToIndex; + this.staticEncoding = staticEncoding; + int h = targetClass.hashCode(); + h = 31 * h + providerClass.hashCode(); + h = 31 * h + schema.hashCode(); + h = 31 * h + Arrays.hashCode(encodingPosToIndex); + h = 31 * h + (staticEncoding ? 1 : 0); + this.hash = h; + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CoderClassKey)) { + return false; + } + CoderClassKey that = (CoderClassKey) o; + return hash == that.hash + && targetClass == that.targetClass + && providerClass == that.providerClass + && staticEncoding == that.staticEncoding + && Arrays.equals(encodingPosToIndex, that.encodingPosToIndex) + && schema.equals(that.schema); + } + } + + /** + * Attempts to generate a direct fused {@link Coder} for {@code typeDescriptor}. Returns {@code + * null} if the type or schema is not eligible for direct bytecode generation. + */ + @SuppressWarnings("unchecked") + static @Nullable Coder tryGenerate( + Schema schema, + TypeDescriptor typeDescriptor, + SerializableFunction toRowFunction, + SerializableFunction fromRowFunction) { + if (!(toRowFunction instanceof GetterBasedSchemaProvider.ToRowWithValueGetters) + || !(fromRowFunction instanceof FromRowUsingCreator)) { + return null; + } + GetterBasedSchemaProvider.ToRowWithValueGetters toRow = + (GetterBasedSchemaProvider.ToRowWithValueGetters) toRowFunction; + FromRowUsingCreator fromRow = (FromRowUsingCreator) fromRowFunction; + GetterBasedSchemaProvider toProvider = toRow.getOuter(); + GetterBasedSchemaProvider fromProvider = fromRow.getSchemaProvider(); + if (toProvider.getClass() != fromProvider.getClass()) { + return null; + } + Class providerClass = toProvider.getClass(); + if (providerClass != JavaFieldSchema.class && providerClass != JavaBeanSchema.class) { + return null; + } + if (!schema.equals(toRow.getSchema()) + || !typeDescriptor.equals(toRow.getTargetType()) + || !typeDescriptor.equals(fromRow.getTypeDescriptor())) { + return null; + } + Set> visited = new HashSet<>(); + return (Coder) + tryGenerateForProvider( + schema, + typeDescriptor, + toProvider, + (SerializableFunction) fromRowFunction, + visited); + } + + @SuppressWarnings("unchecked") + private static @Nullable Coder tryGenerateForProvider( + Schema schema, + TypeDescriptor typeDescriptor, + GetterBasedSchemaProvider provider, + @Nullable SerializableFunction fromRowFn, + Set> visited) { + int fieldCount = schema.getFieldCount(); + if (fieldCount < 1 || fieldCount > MAX_CHUNKED_DIRECT_FIELDS) { + return null; + } + if (schema.getUUID() == null) { + return null; + } + boolean staticEncoding = schema.isStaticEncoding(); + if (staticEncoding && schema.hasNullableFields()) { + return null; + } + Class targetClass = typeDescriptor.getRawType(); + if (!isAccessibleTargetClass(targetClass)) { + return null; + } + // Defer custom @SchemaCreate classes to standard RowCoder delegation. + if (ReflectUtils.getAnnotatedCreateMethod(targetClass) != null + || ReflectUtils.getAnnotatedConstructor(targetClass) != null) { + return null; + } + Constructor noArgCtor; + try { + noArgCtor = targetClass.getDeclaredConstructor(); + } catch (NoSuchMethodException e) { + return null; + } + int ctorMods = noArgCtor.getModifiers(); + if (Modifier.isPrivate(ctorMods) || Modifier.isProtected(ctorMods)) { + return null; + } + if (!visited.add(targetClass)) { + return null; + } + try { + int[] encodingPosToRowIndex = RowCoderGenerator.resolveEncodingPosToRowIndex(schema); + if (encodingPosToRowIndex.length != fieldCount) { + return null; + } + boolean isPojo = provider.getClass() == JavaFieldSchema.class; + FieldSpec[] specsByEncPos = + buildFieldSpecs(schema, typeDescriptor, provider, isPojo, encodingPosToRowIndex, visited); + if (specsByEncPos == null) { + return null; + } + Coder[] subCoders = new Coder[fieldCount]; + for (int pos = 0; pos < fieldCount; pos++) { + subCoders[pos] = specsByEncPos[pos].subCoder; + } + SerializableFunction actualFromRow = + fromRowFn != null ? fromRowFn : new FromRowUsingCreator(typeDescriptor, provider); + + CoderClassKey key = + new CoderClassKey( + targetClass, + provider.getClass(), + schema, + encodingPosToRowIndex.clone(), + staticEncoding); + ConcurrentHashMap> perTypeCache = + CLASS_CACHE.get(targetClass); + Class coderClass = perTypeCache.get(key); + if (coderClass == null) { + if (perTypeCache.size() >= MAX_CLASSES_PER_TYPE) { + return null; + } + boolean hasNullable = schema.hasNullableFields(); + coderClass = + perTypeCache.computeIfAbsent( + key, + k -> generateCoderClass(targetClass, specsByEncPos, staticEncoding, hasNullable)); + } + return coderClass + .getConstructor(Schema.class, SerializableFunction.class, Coder[].class) + .newInstance(schema, actualFromRow, subCoders); + } catch (Exception | LinkageError e) { + LOG.warn("Skipping direct SchemaCoder generation for {}", targetClass.getName(), e); + return null; + } finally { + visited.remove(targetClass); + } + } + + /** + * Verifies that {@code clazz} (and every enclosing class) is accessible from a top-level class + * generated in {@code fromPkg} (not a nestmate). + */ + private static boolean isClassAccessibleFrom(Class clazz, @Nullable Package fromPkg) { + if (clazz.isAnonymousClass() || clazz.isLocalClass() || clazz.isSynthetic()) { + return false; + } + if (clazz.getCanonicalName() == null) { + return false; + } + if (clazz.getEnclosingClass() != null + && !clazz.isInterface() + && !clazz.isEnum() + && !Modifier.isStatic(clazz.getModifiers())) { + return false; + } + for (Class c = clazz; c != null; c = c.getEnclosingClass()) { + int m = c.getModifiers(); + if (Modifier.isPrivate(m) || Modifier.isProtected(m)) { + return false; + } + if (!Modifier.isPublic(m)) { + Package cPkg = c.getPackage(); + if (fromPkg == null || cPkg == null || !fromPkg.getName().equals(cPkg.getName())) { + return false; + } + } + } + return true; + } + + private static boolean isAccessibleTargetClass(Class clazz) { + if (clazz.isPrimitive() + || clazz.isArray() + || clazz.isInterface() + || clazz.isEnum() + || Modifier.isAbstract(clazz.getModifiers())) { + return false; + } + Package pkg = clazz.getPackage(); + if (pkg == null) { + return false; + } + String pkgName = pkg.getName(); + if (pkgName.startsWith("java.") + || pkgName.startsWith("javax.") + || pkgName.startsWith("sun.") + || pkgName.startsWith("jdk.")) { + return false; + } + return isClassAccessibleFrom(clazz, pkg); + } + + private static boolean isSamePackageOrPublic( + Class targetClass, Class declaringClass, int mods) { + if (Modifier.isPrivate(mods) || Modifier.isStatic(mods) || Modifier.isProtected(mods)) { + return false; + } + Package targetPkg = targetClass.getPackage(); + if (!isClassAccessibleFrom(declaringClass, targetPkg)) { + return false; + } + if (Modifier.isPublic(mods)) { + return true; + } + Package declPkg = declaringClass.getPackage(); + return targetPkg != null && declPkg != null && targetPkg.getName().equals(declPkg.getName()); + } + + private static boolean canUseDirectRowEncoding(@Nullable Schema rowSchema) { + return rowSchema != null + && !rowSchema.isEncodingPositionsOverridden() + && !rowSchema.isStaticEncoding() + && !RowCoderGenerator.hasEncodingPositionOverride(rowSchema.getUUID()); + } + + private static @Nullable FieldSpec[] buildFieldSpecs( + Schema schema, + TypeDescriptor targetType, + GetterBasedSchemaProvider provider, + boolean isPojo, + int[] encodingPosToRowIndex, + Set> visited) { + Class targetClass = targetType.getRawType(); + int fieldCount = schema.getFieldCount(); + List typeInfos = + isPojo + ? JavaFieldSchema.JavaFieldTypeSupplier.INSTANCE.get(targetType, schema) + : JavaBeanSchema.GetterTypeSupplier.INSTANCE.get(targetType, schema); + if (typeInfos.size() != fieldCount) { + return null; + } + List setterInfos = null; + if (!isPojo) { + setterInfos = JavaBeanSchema.SetterTypeSupplier.INSTANCE.get(targetType, schema); + if (setterInfos.size() != fieldCount) { + return null; + } + } + + FieldSpec[] specs = new FieldSpec[fieldCount]; + for (int pos = 0; pos < fieldCount; pos++) { + int rowIndex = encodingPosToRowIndex[pos]; + Schema.Field schemaField = schema.getField(rowIndex); + FieldType fieldType = schemaField.getType(); + FieldValueTypeInformation info = typeInfos.get(rowIndex); + if (info == null || !schemaField.getName().equals(info.getName())) { + return null; + } + if (info.getType().hasUnresolvedParameters()) { + return null; + } + Field pojoField = null; + Method getter = null; + Method setter = null; + Class memberClass; + if (isPojo) { + pojoField = info.getField(); + if (pojoField == null) { + return null; + } + int mods = pojoField.getModifiers(); + if (Modifier.isFinal(mods) + || !isSamePackageOrPublic(targetClass, pojoField.getDeclaringClass(), mods)) { + return null; + } + memberClass = pojoField.getType(); + } else { + getter = info.getMethod(); + FieldValueTypeInformation sInfo = setterInfos.get(rowIndex); + if (getter == null || sInfo == null || !schemaField.getName().equals(sInfo.getName())) { + return null; + } + setter = sInfo.getMethod(); + if (setter == null || setter.getParameterCount() != 1) { + return null; + } + if (!isSamePackageOrPublic(targetClass, getter.getDeclaringClass(), getter.getModifiers()) + || !isSamePackageOrPublic( + targetClass, setter.getDeclaringClass(), setter.getModifiers())) { + return null; + } + memberClass = getter.getReturnType(); + if (!memberClass.equals(setter.getParameterTypes()[0])) { + return null; + } + } + // Also guard generic erasure mismatches (e.g., class Holder where getField returns + // Object). + if (!memberClass.equals(info.getRawType())) { + return null; + } + + Coder subCoder = null; + FieldKind kind = + classifyField(targetClass, fieldType, info.getType(), memberClass, provider, visited); + if (kind == null) { + return null; + } + if (kind == FieldKind.SUB_ROW) { + Schema subSchema = fieldType.getRowSchema(); + if (subSchema == null) { + return null; + } + subCoder = tryGenerateForProvider(subSchema, info.getType(), provider, null, visited); + if (subCoder == null) { + return null; + } + } else if (kind == FieldKind.LIST_ROW) { + FieldType elemType = fieldType.getCollectionElementType(); + TypeDescriptor elemTypeDesc = ReflectUtils.getIterableComponentType(info.getType()); + if (elemType == null + || elemType.getNullable() + || elemType.getRowSchema() == null + || elemTypeDesc == null) { + return null; + } + subCoder = + tryGenerateForProvider(elemType.getRowSchema(), elemTypeDesc, provider, null, visited); + if (subCoder == null) { + return null; + } + } + + specs[pos] = + new FieldSpec( + rowIndex, + pos, + schemaField.getName(), + fieldType.getNullable(), + kind, + memberClass, + pojoField, + getter, + setter, + subCoder); + } + return specs; + } + + private static @Nullable FieldKind classifyField( + Class targetClass, + FieldType fieldType, + TypeDescriptor javaTypeDesc, + Class rawClass, + GetterBasedSchemaProvider provider, + Set> visited) { + TypeName tn = fieldType.getTypeName(); + switch (tn) { + case BYTE: + if (rawClass == byte.class) { + return fieldType.getNullable() ? null : FieldKind.PRIM_BYTE; + } + return rawClass == Byte.class ? FieldKind.BOX_BYTE : null; + case INT16: + if (rawClass == short.class) { + return fieldType.getNullable() ? null : FieldKind.PRIM_SHORT; + } + return rawClass == Short.class ? FieldKind.BOX_SHORT : null; + case INT32: + if (rawClass == int.class) { + return fieldType.getNullable() ? null : FieldKind.PRIM_INT; + } + return rawClass == Integer.class ? FieldKind.BOX_INT : null; + case INT64: + if (rawClass == long.class) { + return fieldType.getNullable() ? null : FieldKind.PRIM_LONG; + } + return rawClass == Long.class ? FieldKind.BOX_LONG : null; + case FLOAT: + if (rawClass == float.class) { + return fieldType.getNullable() ? null : FieldKind.PRIM_FLOAT; + } + return rawClass == Float.class ? FieldKind.BOX_FLOAT : null; + case DOUBLE: + if (rawClass == double.class) { + return fieldType.getNullable() ? null : FieldKind.PRIM_DOUBLE; + } + return rawClass == Double.class ? FieldKind.BOX_DOUBLE : null; + case BOOLEAN: + if (rawClass == boolean.class) { + return fieldType.getNullable() ? null : FieldKind.PRIM_BOOL; + } + return rawClass == Boolean.class ? FieldKind.BOX_BOOL : null; + case STRING: + return rawClass == String.class ? FieldKind.STRING : null; + case BYTES: + return rawClass == byte[].class ? FieldKind.BYTES : null; + case DECIMAL: + return rawClass == BigDecimal.class ? FieldKind.DECIMAL : null; + case DATETIME: + if (rawClass == Instant.class) { + return FieldKind.JODA_INSTANT; + } + if (rawClass == org.joda.time.DateTime.class) { + return FieldKind.JODA_DATETIME; + } + return null; + case LOGICAL_TYPE: + LogicalType logical = fieldType.getLogicalType(); + if (logical == null) { + return null; + } + Class lc = logical.getClass(); + if (lc == Date.class && rawClass == LocalDate.class) { + return FieldKind.LOCAL_DATE; + } + if (lc == Time.class && rawClass == LocalTime.class) { + return FieldKind.LOCAL_TIME; + } + if (lc == DateTime.class + && rawClass == LocalDateTime.class + && canUseDirectRowEncoding(DateTime.DATETIME_SCHEMA)) { + return FieldKind.LOCAL_DATETIME; + } + if (lc == UuidLogicalType.class + && rawClass == UUID.class + && canUseDirectRowEncoding(UuidLogicalType.UUID_SCHEMA)) { + return FieldKind.UUID_TYPE; + } + if (lc == NanosInstant.class + && rawClass == java.time.Instant.class + && canUseDirectRowEncoding(logical.getBaseType().getRowSchema())) { + return FieldKind.NANOS_INSTANT; + } + if (lc == MicrosInstant.class + && rawClass == java.time.Instant.class + && canUseDirectRowEncoding(logical.getBaseType().getRowSchema())) { + return FieldKind.MICROS_INSTANT; + } + if (lc == EnumerationType.class + && rawClass.isEnum() + && isClassAccessibleFrom(rawClass, targetClass.getPackage())) { + EnumerationType enumType = (EnumerationType) logical; + Object[] constants = rawClass.getEnumConstants(); + if (constants == null || enumType.getValuesMap().size() != constants.length) { + return null; + } + Map valuesMap = enumType.getValuesMap(); + for (Object c : constants) { + Enum e = (Enum) c; + Integer mapped = valuesMap.get(e.toString()); + if (mapped == null || mapped.intValue() != e.ordinal()) { + return null; + } + } + return FieldKind.ENUM_ORDINAL; + } + return null; + case ARRAY: + if (rawClass != List.class && rawClass != ArrayList.class && rawClass != Collection.class) { + return null; + } + FieldType elemType = fieldType.getCollectionElementType(); + if (elemType == null || elemType.getNullable()) { + return null; + } + TypeDescriptor elemJava = ReflectUtils.getIterableComponentType(javaTypeDesc); + if (elemJava == null) { + return null; + } + Class elemRaw = elemJava.getRawType(); + if (elemType.getTypeName() == TypeName.STRING && elemRaw == String.class) { + return FieldKind.LIST_STRING; + } + if (elemType.getTypeName() == TypeName.INT32 && elemRaw == Integer.class) { + return FieldKind.LIST_INT; + } + if (elemType.getTypeName() == TypeName.INT64 && elemRaw == Long.class) { + return FieldKind.LIST_LONG; + } + if (elemType.getTypeName() == TypeName.DOUBLE && elemRaw == Double.class) { + return FieldKind.LIST_DOUBLE; + } + if (elemType.getTypeName() == TypeName.ROW + && isAccessibleTargetClass(elemRaw) + && isClassAccessibleFrom(elemRaw, targetClass.getPackage())) { + return FieldKind.LIST_ROW; + } + return null; + case MAP: + if (rawClass != Map.class) { + return null; + } + FieldType kt = fieldType.getMapKeyType(); + FieldType vt = fieldType.getMapValueType(); + if (kt == null || vt == null || kt.getNullable() || vt.getNullable()) { + return null; + } + TypeDescriptor keyJava = ReflectUtils.getMapType(javaTypeDesc, 0); + TypeDescriptor valJava = ReflectUtils.getMapType(javaTypeDesc, 1); + if (keyJava == null || valJava == null || keyJava.getRawType() != String.class) { + return null; + } + if (kt.getTypeName() != TypeName.STRING) { + return null; + } + Class vr = valJava.getRawType(); + if (vt.getTypeName() == TypeName.INT64 && vr == Long.class) { + return FieldKind.MAP_STRING_LONG; + } + if (vt.getTypeName() == TypeName.STRING && vr == String.class) { + return FieldKind.MAP_STRING_STRING; + } + if (vt.getTypeName() == TypeName.INT32 && vr == Integer.class) { + return FieldKind.MAP_STRING_INT; + } + if (vt.getTypeName() == TypeName.DOUBLE && vr == Double.class) { + return FieldKind.MAP_STRING_DOUBLE; + } + return null; + case ROW: + if (provider == null + || !isAccessibleTargetClass(rawClass) + || !isClassAccessibleFrom(rawClass, targetClass.getPackage()) + || visited.contains(rawClass)) { + return null; + } + return FieldKind.SUB_ROW; + default: + return null; + } + } + + @SuppressWarnings("unchecked") + private static Class generateCoderClass( + Class targetClass, + FieldSpec[] specsByEncPos, + boolean staticEncoding, + boolean hasNullableFields) { + if (specsByEncPos.length > MAX_DIRECT_FIELDS) { + return generateChunkedCoderClass( + targetClass, specsByEncPos, staticEncoding, hasNullableFields); + } + DynamicType.Builder builder = + BYTE_BUDDY + .with(new InjectPackageStrategy(targetClass)) + .subclass(DirectSchemaCoderBase.class) + .method(ElementMatchers.named("encode").and(ElementMatchers.takesArguments(2))) + .intercept( + new EncodeImpl(targetClass, specsByEncPos, staticEncoding, hasNullableFields)) + .method(ElementMatchers.named("decode").and(ElementMatchers.takesArguments(1))) + .intercept( + new DecodeImpl(targetClass, specsByEncPos, staticEncoding, hasNullableFields)) + .method( + ElementMatchers.named("isRegisterByteSizeObserverCheap") + .and(ElementMatchers.takesArguments(1))) + .intercept(new IsCheapImpl(targetClass, specsByEncPos)) + .method( + ElementMatchers.named("registerByteSizeObserver") + .and(ElementMatchers.takesArguments(2))) + .intercept( + new ByteSizeImpl(targetClass, specsByEncPos, staticEncoding, hasNullableFields)); + + ClassLoader targetLoader = ReflectHelpers.findClassLoader(targetClass.getClassLoader()); + TypePool typePool = + TypePool.Default.of( + new ClassFileLocator.Compound( + ClassFileLocator.ForClassLoader.of(targetLoader), + ClassFileLocator.ForClassLoader.of( + DirectSchemaCoderGenerator.class.getClassLoader()))); + return builder + .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) + .make(typePool) + .load(targetLoader, getClassLoadingStrategy(targetClass)) + .getLoaded(); + } + + private static boolean kindNeedsIsCheapCheck(FieldKind kind) { + switch (kind) { + case STRING: + case LIST_STRING: + case LIST_INT: + case LIST_LONG: + case LIST_DOUBLE: + case LIST_ROW: + case MAP_STRING_LONG: + case MAP_STRING_STRING: + case MAP_STRING_INT: + case MAP_STRING_DOUBLE: + case SUB_ROW: + return true; + default: + return false; + } + } + + private static boolean kindHasDynamicByteSize(FieldKind kind) { + switch (kind) { + case PRIM_BYTE: + case PRIM_BOOL: + case PRIM_SHORT: + case PRIM_FLOAT: + case PRIM_DOUBLE: + return false; + default: + return true; + } + } + + private static Class generateChunkedCoderClass( + Class targetClass, + FieldSpec[] specsByEncPos, + boolean staticEncoding, + boolean hasNullableFields) { + int count = specsByEncPos.length; + int chunkCount = (count + DIRECT_CHUNK_SIZE - 1) / DIRECT_CHUNK_SIZE; + boolean isPojo = specsByEncPos[0].isPojo(); + boolean nullableHeader = hasNullableFields && !staticEncoding; + boolean needsScratch = needsScratchForDecode(specsByEncPos); + + int[] refSlotByPos = new int[count]; + int refCount = 0; + boolean[] chunkHasRefs = new boolean[chunkCount]; + boolean[] chunkNeedsIsCheap = new boolean[chunkCount]; + boolean[] chunkHasNullable = new boolean[chunkCount]; + boolean[] chunkNeedsByteSize = new boolean[chunkCount]; + boolean anyNeedsIsCheap = false; + for (int c = 0; c < chunkCount; c++) { + int start = c * DIRECT_CHUNK_SIZE; + int end = Math.min(start + DIRECT_CHUNK_SIZE, count); + for (int pos = start; pos < end; pos++) { + FieldSpec spec = specsByEncPos[pos]; + if (!spec.kind.isPrimitive()) { + refSlotByPos[pos] = refCount++; + chunkHasRefs[c] = true; + } else { + refSlotByPos[pos] = -1; + } + if (kindNeedsIsCheapCheck(spec.kind)) { + chunkNeedsIsCheap[c] = true; + anyNeedsIsCheap = true; + } + if (spec.nullable) { + chunkHasNullable[c] = true; + } + if (kindHasDynamicByteSize(spec.kind)) { + chunkNeedsByteSize[c] = true; + } + } + } + + DynamicType.Builder builder = + BYTE_BUDDY + .with(new InjectPackageStrategy(targetClass)) + .subclass(DirectSchemaCoderBase.class); + + for (int c = 0; c < chunkCount; c++) { + int start = c * DIRECT_CHUNK_SIZE; + int end = Math.min(start + DIRECT_CHUNK_SIZE, count); + if (nullableHeader && !isPojo) { + if (chunkHasRefs[c]) { + builder = + builder + .defineMethod("nullScanBeanC" + c, int.class, Visibility.PRIVATE) + .withParameters(targetClass, Object[].class) + .intercept(new NullScanChunkImpl(specsByEncPos, start, end, true, refSlotByPos)) + .defineMethod("encBeanC" + c, int.class, Visibility.PRIVATE) + .withParameters( + targetClass, Object[].class, OutputStream.class, byte[].class, int.class) + .throwing(IOException.class) + .intercept(new EncodeChunkImpl(specsByEncPos, start, end, true, refSlotByPos)); + } else { + builder = + builder + .defineMethod("encC" + c, int.class, Visibility.PRIVATE) + .withParameters(targetClass, OutputStream.class, byte[].class, int.class) + .throwing(IOException.class) + .intercept(new EncodeChunkImpl(specsByEncPos, start, end, false, refSlotByPos)); + } + } else { + if (nullableHeader && chunkHasRefs[c]) { + builder = + builder + .defineMethod("nullScanC" + c, int.class, Visibility.PRIVATE) + .withParameters(targetClass) + .intercept(new NullScanChunkImpl(specsByEncPos, start, end, false, refSlotByPos)); + } + builder = + builder + .defineMethod("encC" + c, int.class, Visibility.PRIVATE) + .withParameters(targetClass, OutputStream.class, byte[].class, int.class) + .throwing(IOException.class) + .intercept(new EncodeChunkImpl(specsByEncPos, start, end, false, refSlotByPos)); + } + + builder = + builder + .defineMethod("decNoNullC" + c, void.class, Visibility.PRIVATE) + .withParameters(targetClass, InputStream.class, byte[].class) + .throwing(IOException.class) + .intercept(new DecodeChunkImpl(specsByEncPos, start, end, false)); + if (nullableHeader) { + builder = + builder + .defineMethod("decNullC" + c, void.class, Visibility.PRIVATE) + .withParameters(targetClass, InputStream.class, byte[].class, int.class) + .throwing(IOException.class) + .intercept(new DecodeChunkImpl(specsByEncPos, start, end, true)); + } + + if (chunkNeedsIsCheap[c]) { + builder = + builder + .defineMethod("isCheapC" + c, boolean.class, Visibility.PRIVATE) + .withParameters(targetClass) + .intercept(new IsCheapChunkImpl(specsByEncPos, start, end)); + } + if (chunkNeedsByteSize[c]) { + builder = + builder + .defineMethod("sizeC" + c, long.class, Visibility.PRIVATE) + .withParameters(targetClass, ElementByteSizeObserver.class) + .throwing(Exception.class) + .intercept( + new ByteSizeChunkImpl( + specsByEncPos, start, end, !staticEncoding && chunkHasNullable[c])); + } + } + + builder = + builder + .method(ElementMatchers.named("encode").and(ElementMatchers.takesArguments(2))) + .intercept( + new ChunkedEncodeImpl( + targetClass, + count, + chunkCount, + staticEncoding, + hasNullableFields, + isPojo, + refCount, + chunkHasRefs)) + .method(ElementMatchers.named("decode").and(ElementMatchers.takesArguments(1))) + .intercept( + new ChunkedDecodeImpl( + targetClass, + count, + chunkCount, + staticEncoding, + hasNullableFields, + needsScratch)) + .method( + ElementMatchers.named("isRegisterByteSizeObserverCheap") + .and(ElementMatchers.takesArguments(1))) + .intercept(new ChunkedIsCheapImpl(targetClass, chunkNeedsIsCheap, anyNeedsIsCheap)) + .method( + ElementMatchers.named("registerByteSizeObserver") + .and(ElementMatchers.takesArguments(2))) + .intercept( + new ChunkedByteSizeImpl( + targetClass, + specsByEncPos, + chunkCount, + staticEncoding, + hasNullableFields, + chunkNeedsByteSize, + chunkHasNullable)); + + ClassLoader targetLoader = ReflectHelpers.findClassLoader(targetClass.getClassLoader()); + TypePool typePool = + TypePool.Default.of( + new ClassFileLocator.Compound( + ClassFileLocator.ForClassLoader.of(targetLoader), + ClassFileLocator.ForClassLoader.of( + DirectSchemaCoderGenerator.class.getClassLoader()))); + return builder + .visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)) + .make(typePool) + .load(targetLoader, getClassLoadingStrategy(targetClass)) + .getLoaded(); + } + + private static void pushInt(MethodVisitor mv, int value) { + if (value >= -1 && value <= 5) { + mv.visitInsn(Opcodes.ICONST_0 + value); + } else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + mv.visitIntInsn(Opcodes.BIPUSH, value); + } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) { + mv.visitIntInsn(Opcodes.SIPUSH, value); + } else { + mv.visitLdcInsn(value); + } + } + + private static void emitReadMember(MethodVisitor mv, int objLocal, FieldSpec spec) { + mv.visitVarInsn(Opcodes.ALOAD, objLocal); + if (spec.isPojo()) { + Field f = spec.pojoField; + mv.visitFieldInsn( + Opcodes.GETFIELD, + Type.getInternalName(f.getDeclaringClass()), + f.getName(), + Type.getDescriptor(f.getType())); + } else { + Method g = spec.getter; + boolean isInterface = g.getDeclaringClass().isInterface(); + mv.visitMethodInsn( + isInterface ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL, + Type.getInternalName(g.getDeclaringClass()), + g.getName(), + Type.getMethodDescriptor(g), + isInterface); + } + } + + private static void emitWriteMember(MethodVisitor mv, FieldSpec spec) { + if (spec.isPojo()) { + Field f = spec.pojoField; + mv.visitFieldInsn( + Opcodes.PUTFIELD, + Type.getInternalName(f.getDeclaringClass()), + f.getName(), + Type.getDescriptor(f.getType())); + } else { + Method s = spec.setter; + boolean isInterface = s.getDeclaringClass().isInterface(); + mv.visitMethodInsn( + isInterface ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL, + Type.getInternalName(s.getDeclaringClass()), + s.getName(), + Type.getMethodDescriptor(s), + isInterface); + Class ret = s.getReturnType(); + if (ret == long.class || ret == double.class) { + mv.visitInsn(Opcodes.POP2); + } else if (ret != void.class) { + mv.visitInsn(Opcodes.POP); + } + } + } + + private static void emitThrowNullNonNullable(MethodVisitor mv, int rowIndex) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "schema", "Lorg/apache/beam/sdk/schemas/Schema;"); + pushInt(mv, rowIndex); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "nullNonNullableField", + "(Lorg/apache/beam/sdk/schemas/Schema;I)Ljava/lang/RuntimeException;", + false); + mv.visitInsn(Opcodes.ATHROW); + } + + private static final String PACK_SUFFIX = "[BI" + OUT_DESC + ")I"; + + private static void emitPackCall( + MethodVisitor mv, String method, String desc, int bufLocal, int posLocal, int outLocal) { + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitVarInsn(Opcodes.ILOAD, posLocal); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, WIRE_CODEC, method, desc, false); + mv.visitVarInsn(Opcodes.ISTORE, posLocal); + } + + private static void emitFlush(MethodVisitor mv, int bufLocal, int posLocal, int outLocal) { + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitVarInsn(Opcodes.ILOAD, posLocal); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, WIRE_CODEC, "flush", "([BI" + OUT_DESC + ")I", false); + mv.visitVarInsn(Opcodes.ISTORE, posLocal); + } + + private static void emitPackNonNullValue( + MethodVisitor mv, FieldSpec spec, int valLocal, int outLocal, int bufLocal, int posLocal) { + switch (spec.kind) { + case BOX_BYTE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B", false); + emitPackCall(mv, "packByte", "(B" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case BOX_SHORT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S", false); + emitPackCall(mv, "packInt16", "(S" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case BOX_INT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); + emitPackCall(mv, "packVarInt", "(I" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case BOX_LONG: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J", false); + emitPackCall(mv, "packVarLong", "(J" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case BOX_FLOAT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F", false); + emitPackCall(mv, "packFloat", "(F" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case BOX_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D", false); + emitPackCall(mv, "packDouble", "(D" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case BOX_BOOL: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false); + emitPackCall(mv, "packBoolean", "(Z" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case STRING: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, "packString", "(Ljava/lang/String;" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case BYTES: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall(mv, "packBytes", "([B" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case DECIMAL: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packDecimal", + "(Ljava/math/BigDecimal;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case JODA_INSTANT: + case JODA_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packDateTime", + "(Lorg/joda/time/ReadableInstant;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case LOCAL_DATE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packLocalDate", + "(Ljava/time/LocalDate;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case LOCAL_TIME: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packLocalTime", + "(Ljava/time/LocalTime;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case LOCAL_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packLocalDateTime", + "(Ljava/time/LocalDateTime;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case UUID_TYPE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, "packUuid", "(Ljava/util/UUID;" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case NANOS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packNanosInstant", + "(Ljava/time/Instant;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case MICROS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packMicrosInstant", + "(Ljava/time/Instant;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case ENUM_ORDINAL: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Enum", "ordinal", "()I", false); + emitPackCall(mv, "packVarInt", "(I" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case LIST_STRING: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packStringCollection", + "(Ljava/util/Collection;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case LIST_INT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packInt32Collection", + "(Ljava/util/Collection;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case LIST_LONG: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packInt64Collection", + "(Ljava/util/Collection;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case LIST_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packDoubleCollection", + "(Ljava/util/Collection;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case LIST_ROW: + // Flush buffered prefix bytes to out before invoking nested element coder so wire order is + // strictly preserved (ScratchPool already isolates nested buffers). + emitFlush(mv, bufLocal, posLocal, outLocal); + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "subCoders", "[Lorg/apache/beam/sdk/coders/Coder;"); + pushInt(mv, spec.encPos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "writeElementCollection", + "(Ljava/util/Collection;Lorg/apache/beam/sdk/coders/Coder;" + OUT_DESC + ")V", + false); + break; + case MAP_STRING_LONG: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packStringLongMap", + "(Ljava/util/Map;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case MAP_STRING_STRING: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packStringStringMap", + "(Ljava/util/Map;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case MAP_STRING_INT: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, "packStringIntMap", "(Ljava/util/Map;" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case MAP_STRING_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + emitPackCall( + mv, + "packStringDoubleMap", + "(Ljava/util/Map;" + PACK_SUFFIX, + bufLocal, + posLocal, + outLocal); + break; + case SUB_ROW: + // Flush buffered prefix bytes to out before invoking nested sub-coder so wire order is + // strictly preserved (ScratchPool already isolates nested buffers). + emitFlush(mv, bufLocal, posLocal, outLocal); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "subCoders", "[Lorg/apache/beam/sdk/coders/Coder;"); + pushInt(mv, spec.encPos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, valLocal); + mv.visitVarInsn(Opcodes.ALOAD, outLocal); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + CODER_TYPE, + "encode", + "(Ljava/lang/Object;" + OUT_DESC + ")V", + false); + break; + default: + throw new AssertionError("Unexpected reference kind: " + spec.kind); + } + } + + private static void emitPackPrimitive( + MethodVisitor mv, FieldSpec spec, int objLocal, int outLocal, int bufLocal, int posLocal) { + emitReadMember(mv, objLocal, spec); + switch (spec.kind) { + case PRIM_BYTE: + emitPackCall(mv, "packByte", "(B" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case PRIM_SHORT: + emitPackCall(mv, "packInt16", "(S" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case PRIM_INT: + emitPackCall(mv, "packVarInt", "(I" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case PRIM_LONG: + emitPackCall(mv, "packVarLong", "(J" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case PRIM_FLOAT: + emitPackCall(mv, "packFloat", "(F" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case PRIM_DOUBLE: + emitPackCall(mv, "packDouble", "(D" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + case PRIM_BOOL: + emitPackCall(mv, "packBoolean", "(Z" + PACK_SUFFIX, bufLocal, posLocal, outLocal); + break; + default: + throw new AssertionError("Unexpected primitive kind: " + spec.kind); + } + } + + private static void emitReadValueForDecode( + MethodVisitor mv, FieldSpec spec, int inLocal, int bufLocal) { + switch (spec.kind) { + case PRIM_BYTE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readByte", "(" + IN_DESC + ")B", false); + break; + case PRIM_SHORT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readInt16", "(" + IN_DESC + "[B)S", false); + break; + case PRIM_INT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + break; + case PRIM_LONG: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarLong", "(" + IN_DESC + ")J", false); + break; + case PRIM_FLOAT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readFloat", "(" + IN_DESC + "[B)F", false); + break; + case PRIM_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readDouble", "(" + IN_DESC + "[B)D", false); + break; + case PRIM_BOOL: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readBoolean", "(" + IN_DESC + ")Z", false); + break; + case BOX_BYTE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readByte", "(" + IN_DESC + ")B", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false); + break; + case BOX_SHORT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readInt16", "(" + IN_DESC + "[B)S", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false); + break; + case BOX_INT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); + break; + case BOX_LONG: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarLong", "(" + IN_DESC + ")J", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); + break; + case BOX_FLOAT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readFloat", "(" + IN_DESC + "[B)F", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false); + break; + case BOX_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readDouble", "(" + IN_DESC + "[B)D", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false); + break; + case BOX_BOOL: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readBoolean", "(" + IN_DESC + ")Z", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); + break; + case STRING: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readString", + "(" + IN_DESC + "[B)Ljava/lang/String;", + false); + break; + case BYTES: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readBytes", "(" + IN_DESC + ")[B", false); + break; + case DECIMAL: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readDecimal", + "(" + IN_DESC + "[B)Ljava/math/BigDecimal;", + false); + break; + case JODA_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readDateTime", + "(" + IN_DESC + "[B)Lorg/joda/time/Instant;", + false); + break; + case JODA_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + GEN_TYPE, + "readJodaDateTime", + "(" + IN_DESC + "[B)Lorg/joda/time/DateTime;", + false); + break; + case LOCAL_DATE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readLocalDate", + "(" + IN_DESC + ")Ljava/time/LocalDate;", + false); + break; + case LOCAL_TIME: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readLocalTime", + "(" + IN_DESC + ")Ljava/time/LocalTime;", + false); + break; + case LOCAL_DATETIME: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readLocalDateTime", + "(" + IN_DESC + ")Ljava/time/LocalDateTime;", + false); + break; + case UUID_TYPE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readUuid", + "(" + IN_DESC + ")Ljava/util/UUID;", + false); + break; + case NANOS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readNanosInstant", + "(" + IN_DESC + ")Ljava/time/Instant;", + false); + break; + case MICROS_INSTANT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readMicrosInstant", + "(" + IN_DESC + ")Ljava/time/Instant;", + false); + break; + case ENUM_ORDINAL: + mv.visitLdcInsn(Type.getType(spec.javaType)); + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + GEN_TYPE, + "enumConstantForOrdinal", + "(Ljava/lang/Class;I)Ljava/lang/Object;", + false); + mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(spec.javaType)); + break; + case LIST_STRING: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readStringList", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + if (spec.javaType == ArrayList.class) { + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/ArrayList"); + } + break; + case LIST_INT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readInt32List", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + if (spec.javaType == ArrayList.class) { + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/ArrayList"); + } + break; + case LIST_LONG: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readInt64List", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + if (spec.javaType == ArrayList.class) { + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/ArrayList"); + } + break; + case LIST_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readDoubleList", + "(" + IN_DESC + "[B)Ljava/util/List;", + false); + if (spec.javaType == ArrayList.class) { + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/ArrayList"); + } + break; + case LIST_ROW: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "subCoders", "[Lorg/apache/beam/sdk/coders/Coder;"); + pushInt(mv, spec.encPos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readElementList", + "(" + IN_DESC + "Lorg/apache/beam/sdk/coders/Coder;)Ljava/util/List;", + false); + if (spec.javaType == ArrayList.class) { + mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/ArrayList"); + } + break; + case MAP_STRING_LONG: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readStringLongMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + case MAP_STRING_STRING: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readStringStringMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + case MAP_STRING_INT: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readStringIntMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + case MAP_STRING_DOUBLE: + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "readStringDoubleMap", + "(" + IN_DESC + "[B)Ljava/util/Map;", + false); + break; + case SUB_ROW: + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "subCoders", "[Lorg/apache/beam/sdk/coders/Coder;"); + pushInt(mv, spec.encPos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + CODER_TYPE, + "decode", + "(" + IN_DESC + ")Ljava/lang/Object;", + false); + mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(spec.javaType)); + break; + } + } + + private static final class EncodeImpl implements Implementation { + private final Class targetClass; + private final FieldSpec[] specs; + private final boolean staticEncoding; + private final boolean hasNullableFields; + + EncodeImpl( + Class targetClass, + FieldSpec[] specs, + boolean staticEncoding, + boolean hasNullableFields) { + this.targetClass = targetClass; + this.specs = specs; + this.staticEncoding = staticEncoding; + this.hasNullableFields = hasNullableFields; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + int count = specs.length; + String targetInternal = Type.getInternalName(targetClass); + // Slots: 0=this, 1=rawValue, 2=out, 3=typedObj + Label nonNullArg = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitJumpInsn(Opcodes.IFNONNULL, nonNullArg); + mv.visitLdcInsn(targetClass.getSimpleName()); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "cannotEncodeNull", + "(Ljava/lang/String;)Ljava/io/IOException;", + false); + mv.visitInsn(Opcodes.ATHROW); + mv.visitLabel(nonNullArg); + + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitTypeInsn(Opcodes.CHECKCAST, targetInternal); + mv.visitVarInsn(Opcodes.ASTORE, 3); + + if (!hasNullableFields) { + // Slots: 4=tempRef, 5=pool, 6=buf, 7=pos, 8=ex + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 5); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 6); + + mv.visitLabel(tryStart); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ISTORE, 7); + if (!staticEncoding) { + pushInt(mv, count); + mv.visitInsn(Opcodes.LCONST_0); + emitPackCall(mv, "packHeader", "(IJ" + PACK_SUFFIX, 6, 7, 2); + } + for (int pos = 0; pos < count; pos++) { + FieldSpec spec = specs[pos]; + if (spec.kind.isPrimitive()) { + emitPackPrimitive(mv, spec, 3, 2, 6, 7); + } else { + emitReadMember(mv, 3, spec); + mv.visitVarInsn(Opcodes.ASTORE, 4); + Label ok = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitJumpInsn(Opcodes.IFNONNULL, ok); + emitThrowNullNonNullable(mv, spec.rowIndex); + mv.visitLabel(ok); + emitPackNonNullValue(mv, spec, 4, 2, 6, 7); + } + } + emitFlush(mv, 6, 7, 2); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, 8); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 8); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(8, 9); + } + + // Nullable schema: evaluate each reference member ONCE into its own local, build long mask. + // Slots: 4..5=nullMask, 6=pool, 7=buf, 8=pos, 9=ex, ref locals start at 10. + int[] refSlots = new int[count]; + int nextSlot = 10; + mv.visitInsn(Opcodes.LCONST_0); + mv.visitVarInsn(Opcodes.LSTORE, 4); + for (int pos = 0; pos < count; pos++) { + FieldSpec spec = specs[pos]; + if (spec.kind.isPrimitive()) { + continue; + } + int slot = nextSlot++; + refSlots[pos] = slot; + emitReadMember(mv, 3, spec); + mv.visitVarInsn(Opcodes.ASTORE, slot); + Label notNull = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, slot); + mv.visitJumpInsn(Opcodes.IFNONNULL, notNull); + if (!spec.nullable) { + emitThrowNullNonNullable(mv, spec.rowIndex); + } else { + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitLdcInsn(1L << pos); + mv.visitInsn(Opcodes.LOR); + mv.visitVarInsn(Opcodes.LSTORE, 4); + } + mv.visitLabel(notNull); + } + + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 6); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 7); + + mv.visitLabel(tryStart); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ISTORE, 8); + pushInt(mv, count); + mv.visitVarInsn(Opcodes.LLOAD, 4); + emitPackCall(mv, "packHeader", "(IJ" + PACK_SUFFIX, 7, 8, 2); + + for (int pos = 0; pos < count; pos++) { + FieldSpec spec = specs[pos]; + if (spec.kind.isPrimitive()) { + emitPackPrimitive(mv, spec, 3, 2, 7, 8); + } else if (!spec.nullable) { + emitPackNonNullValue(mv, spec, refSlots[pos], 2, 7, 8); + } else { + Label skip = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, refSlots[pos]); + mv.visitJumpInsn(Opcodes.IFNULL, skip); + emitPackNonNullValue(mv, spec, refSlots[pos], 2, 7, 8); + mv.visitLabel(skip); + } + } + emitFlush(mv, 7, 8, 2); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, 9); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 9); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(8, nextSlot); + }; + } + } + + private static boolean needsScratchForDecode(FieldSpec[] specs) { + for (FieldSpec spec : specs) { + switch (spec.kind) { + case PRIM_SHORT: + case PRIM_FLOAT: + case PRIM_DOUBLE: + case BOX_SHORT: + case BOX_FLOAT: + case BOX_DOUBLE: + case STRING: + case DECIMAL: + case JODA_INSTANT: + case JODA_DATETIME: + case LIST_STRING: + case LIST_INT: + case LIST_LONG: + case LIST_DOUBLE: + case MAP_STRING_LONG: + case MAP_STRING_STRING: + case MAP_STRING_INT: + case MAP_STRING_DOUBLE: + return true; + default: + break; + } + } + return false; + } + + private static final class DecodeImpl implements Implementation { + private final Class targetClass; + private final FieldSpec[] specs; + private final boolean staticEncoding; + private final boolean hasNullableFields; + + DecodeImpl( + Class targetClass, + FieldSpec[] specs, + boolean staticEncoding, + boolean hasNullableFields) { + this.targetClass = targetClass; + this.specs = specs; + this.staticEncoding = staticEncoding; + this.hasNullableFields = hasNullableFields; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + int count = specs.length; + String targetInternal = Type.getInternalName(targetClass); + boolean needsScratch = needsScratchForDecode(specs); + // Decode-side scratch buffer holds no bytes live across field boundaries and is checked out + // exclusively from ScratchPool, so nested subCoder.decode calls can never corrupt outer + // decode state. + if (staticEncoding) { + // Slots: 0=this, 1=in, 2=res, [3=pool, 4=buf, 5=ex] + if (!needsScratch) { + emitNewTarget(mv, targetInternal, 2); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + emitReadValueForDecode(mv, specs[pos], 1, -1); + emitWriteMember(mv, specs[pos]); + } + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + return new ByteCodeAppender.Size(6, 3); + } + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 3); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 4); + + mv.visitLabel(tryStart); + emitNewTarget(mv, targetInternal, 2); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + emitReadValueForDecode(mv, specs[pos], 1, 4); + emitWriteMember(mv, specs[pos]); + } + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, 5); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(6, 6); + } + + // Slots: 0=this, 1=in, 2=res, 3=streamFieldCount, 4=nullByteLen, 5..6=nullMask, + // 7=pool, 8=buf, 9=ex + // streamFieldCount = readVarInt(in) + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + mv.visitVarInsn(Opcodes.ISTORE, 3); + + Label matchingCount = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 3); + pushInt(mv, count); + mv.visitJumpInsn(Opcodes.IF_ICMPEQ, matchingCount); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ILOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + BASE_TYPE, + "decodeEvolved", + "(I" + IN_DESC + ")Ljava/lang/Object;", + false); + mv.visitInsn(Opcodes.ARETURN); + mv.visitLabel(matchingCount); + + // nullByteLen = readVarInt(in) + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + mv.visitVarInsn(Opcodes.ISTORE, 4); + + Label badNullLen = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFLT, badNullLen); + + if (!hasNullableFields) { + Label fallbackNulls = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFNE, fallbackNulls); + if (!needsScratch) { + emitNewTarget(mv, targetInternal, 2); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + emitReadValueForDecode(mv, specs[pos], 1, -1); + emitWriteMember(mv, specs[pos]); + } + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + } else { + // Slots on fast path: 5=pool, 6=buf, 7=ex + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 5); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 6); + + mv.visitLabel(tryStart); + emitNewTarget(mv, targetInternal, 2); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + emitReadValueForDecode(mv, specs[pos], 1, 6); + emitWriteMember(mv, specs[pos]); + } + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, 7); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitInsn(Opcodes.ATHROW); + } + + mv.visitLabel(fallbackNulls); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ILOAD, 3); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + BASE_TYPE, + "decodeEvolvedAfterNullLen", + "(II" + IN_DESC + ")Ljava/lang/Object;", + false); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(badNullLen); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "invalidNullBitmapLength", + "(I)Ljava/io/IOException;", + false); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(6, needsScratch ? 8 : 5); + } + + // Nullable schema: handle nullByteLen == 0 (or 1..8) directly; > 8 falls back cleanly. + Label hasNulls = new Label(); + Label wideNulls = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 4); + pushInt(mv, 8); + mv.visitJumpInsn(Opcodes.IF_ICMPGT, wideNulls); + + if (needsScratch) { + // Acquire one scratch buffer covering null mask + all field decodes. + // Slots: 5..6=nullMask, 7=pool, 8=buf, 9=ex + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label retLabel = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 7); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 8); + + mv.visitLabel(tryStart); + if (count <= 32) { + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFNE, hasNulls); + emitNewTarget(mv, targetInternal, 2); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + emitReadValueForDecode(mv, specs[pos], 1, 8); + emitWriteMember(mv, specs[pos]); + } + mv.visitJumpInsn(Opcodes.GOTO, retLabel); + + mv.visitLabel(hasNulls); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 8); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readNullMask", "(" + IN_DESC + "I[B)J", false); + mv.visitVarInsn(Opcodes.LSTORE, 5); + } else { + Label afterMask = new Label(); + mv.visitInsn(Opcodes.LCONST_0); + mv.visitVarInsn(Opcodes.LSTORE, 5); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFEQ, afterMask); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 8); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readNullMask", "(" + IN_DESC + "I[B)J", false); + mv.visitVarInsn(Opcodes.LSTORE, 5); + mv.visitLabel(afterMask); + } + + emitMaskedDecodeFields(mv, targetInternal, count, 8); + mv.visitLabel(retLabel); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitVarInsn(Opcodes.ALOAD, 8); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, 9); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitVarInsn(Opcodes.ALOAD, 8); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 9); + mv.visitInsn(Opcodes.ATHROW); + } else { + // No field uses buf: avoid ThreadLocal lookup completely when nullByteLen == 0, and + // borrow/release buf solely around readNullMask when nullByteLen > 0. + if (count <= 32) { + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFNE, hasNulls); + emitNewTarget(mv, targetInternal, 2); + for (int pos = 0; pos < count; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + emitReadValueForDecode(mv, specs[pos], 1, -1); + emitWriteMember(mv, specs[pos]); + } + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(hasNulls); + emitReadNullMaskWithPool(mv, 1, 4, 5, 7, 8, 9); + } else { + Label afterMask = new Label(); + mv.visitInsn(Opcodes.LCONST_0); + mv.visitVarInsn(Opcodes.LSTORE, 5); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFEQ, afterMask); + emitReadNullMaskWithPool(mv, 1, 4, 5, 7, 8, 9); + mv.visitLabel(afterMask); + } + + emitMaskedDecodeFields(mv, targetInternal, count, -1); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + } + + mv.visitLabel(wideNulls); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ILOAD, 3); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + BASE_TYPE, + "decodeEvolvedAfterNullLen", + "(II" + IN_DESC + ")Ljava/lang/Object;", + false); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(badNullLen); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "invalidNullBitmapLength", + "(I)Ljava/io/IOException;", + false); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(6, 10); + }; + } + + private void emitReadNullMaskWithPool( + MethodVisitor mv, + int inLocal, + int lenLocal, + int maskLocal, + int poolLocal, + int bufLocal, + int exLocal) { + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + Label after = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, bufLocal); + + mv.visitLabel(tryStart); + mv.visitVarInsn(Opcodes.ALOAD, inLocal); + mv.visitVarInsn(Opcodes.ILOAD, lenLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readNullMask", "(" + IN_DESC + "I[B)J", false); + mv.visitVarInsn(Opcodes.LSTORE, maskLocal); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitJumpInsn(Opcodes.GOTO, after); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, exLocal); + mv.visitVarInsn(Opcodes.ALOAD, poolLocal); + mv.visitVarInsn(Opcodes.ALOAD, bufLocal); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, exLocal); + mv.visitInsn(Opcodes.ATHROW); + + mv.visitLabel(after); + } + + private void emitMaskedDecodeFields( + MethodVisitor mv, String targetInternal, int count, int bufLocal) { + emitNewTarget(mv, targetInternal, 2); + for (int pos = 0; pos < count; pos++) { + FieldSpec spec = specs[pos]; + Label isNull = new Label(); + Label done = new Label(); + mv.visitVarInsn(Opcodes.LLOAD, 5); + mv.visitLdcInsn(1L << pos); + mv.visitInsn(Opcodes.LAND); + mv.visitInsn(Opcodes.LCONST_0); + mv.visitInsn(Opcodes.LCMP); + mv.visitJumpInsn(Opcodes.IFNE, isNull); + mv.visitVarInsn(Opcodes.ALOAD, 2); + emitReadValueForDecode(mv, spec, 1, bufLocal); + emitWriteMember(mv, spec); + mv.visitJumpInsn(Opcodes.GOTO, done); + + mv.visitLabel(isNull); + if (spec.kind.isPrimitive()) { + mv.visitLdcInsn(spec.schemaFieldName); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "nullPrimitive", + "(Ljava/lang/String;)Ljava/lang/NullPointerException;", + false); + mv.visitInsn(Opcodes.ATHROW); + } else { + // Explicitly write null to overwrite any non-null default field initializer in ctor. + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ACONST_NULL); + emitWriteMember(mv, spec); + } + mv.visitLabel(done); + } + } + } + + private static void emitNewTarget(MethodVisitor mv, String targetInternal, int localSlot) { + mv.visitTypeInsn(Opcodes.NEW, targetInternal); + mv.visitInsn(Opcodes.DUP); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, targetInternal, "", "()V", false); + mv.visitVarInsn(Opcodes.ASTORE, localSlot); + } + + private static void emitNonNullArgCheck(MethodVisitor mv, Class targetClass) { + Label nonNullArg = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitJumpInsn(Opcodes.IFNONNULL, nonNullArg); + mv.visitLdcInsn(targetClass.getSimpleName()); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "cannotEncodeNull", + "(Ljava/lang/String;)Ljava/io/IOException;", + false); + mv.visitInsn(Opcodes.ATHROW); + mv.visitLabel(nonNullArg); + } + + private static void emitIsCheapRange( + MethodVisitor mv, FieldSpec[] specs, int start, int end, int objSlot, int tempSlot) { + for (int pos = start; pos < end; pos++) { + FieldSpec spec = specs[pos]; + switch (spec.kind) { + case STRING: + emitReadMember(mv, objSlot, spec); + mv.visitVarInsn(Opcodes.ASTORE, tempSlot); + Label sOk = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitJumpInsn(Opcodes.IFNULL, sOk); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "length", "()I", false); + pushInt(mv, 1024); + mv.visitJumpInsn(Opcodes.IF_ICMPLE, sOk); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(sOk); + break; + case LIST_STRING: + case LIST_INT: + case LIST_LONG: + case LIST_DOUBLE: + case LIST_ROW: + // Cheap when null or an ElementByteSizeObservableIterable (matches ListCoder). + emitReadMember(mv, objSlot, spec); + mv.visitVarInsn(Opcodes.ASTORE, tempSlot); + Label lOk = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitJumpInsn(Opcodes.IFNULL, lOk); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitTypeInsn(Opcodes.INSTANCEOF, OBSERVABLE_ITERABLE_TYPE); + mv.visitJumpInsn(Opcodes.IFNE, lOk); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(lOk); + break; + case MAP_STRING_LONG: + case MAP_STRING_STRING: + case MAP_STRING_INT: + case MAP_STRING_DOUBLE: + // Only cheap when null (matches RowCoderGenerator delegating to MapCoder). + emitReadMember(mv, objSlot, spec); + Label cOk = new Label(); + mv.visitJumpInsn(Opcodes.IFNULL, cOk); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(cOk); + break; + case SUB_ROW: + emitReadMember(mv, objSlot, spec); + mv.visitVarInsn(Opcodes.ASTORE, tempSlot); + Label rOk = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitJumpInsn(Opcodes.IFNULL, rOk); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "subCoders", "[Lorg/apache/beam/sdk/coders/Coder;"); + pushInt(mv, spec.encPos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + CODER_TYPE, + "isRegisterByteSizeObserverCheap", + "(Ljava/lang/Object;)Z", + false); + mv.visitJumpInsn(Opcodes.IFNE, rOk); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(rOk); + break; + default: + break; + } + } + } + + private static long computeFixedConstBytes( + FieldSpec[] specs, boolean staticEncoding, boolean hasNullableFields) { + long constBytes = 0L; + if (!staticEncoding) { + constBytes += VarInt.getLength(specs.length); + if (!hasNullableFields) { + constBytes += 1L; // Empty null bitmask byte (0x00). + } + } + for (FieldSpec spec : specs) { + switch (spec.kind) { + case PRIM_BYTE: + case PRIM_BOOL: + constBytes += 1L; + break; + case PRIM_SHORT: + constBytes += 2L; + break; + case PRIM_FLOAT: + constBytes += 4L; + break; + case PRIM_DOUBLE: + constBytes += 8L; + break; + default: + break; + } + } + return constBytes; + } + + private static final class IsCheapImpl implements Implementation { + private final Class targetClass; + private final FieldSpec[] specs; + + IsCheapImpl(Class targetClass, FieldSpec[] specs) { + this.targetClass = targetClass; + this.specs = specs; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + // Slots: 0=this, 1=rawValue, 2=typedObj, 3=tempRef + // Return false on null, strings > 1024 chars, non-null Maps, or non-observable Collections. + Label nonNull = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitJumpInsn(Opcodes.IFNONNULL, nonNull); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(nonNull); + + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(targetClass)); + mv.visitVarInsn(Opcodes.ASTORE, 2); + + emitIsCheapRange(mv, specs, 0, specs.length, 2, 3); + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(4, 4); + }; + } + } + + private static final class ByteSizeImpl implements Implementation { + private final Class targetClass; + private final FieldSpec[] specs; + private final boolean staticEncoding; + private final boolean hasNullableFields; + + ByteSizeImpl( + Class targetClass, + FieldSpec[] specs, + boolean staticEncoding, + boolean hasNullableFields) { + this.targetClass = targetClass; + this.specs = specs; + this.staticEncoding = staticEncoding; + this.hasNullableFields = hasNullableFields; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + int count = specs.length; + // Slots: 0=this, 1=rawValue, 2=observer, 3=obj, 4..5=total, 6=highestNull, 7=tempRef + Label nonNullArg = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitJumpInsn(Opcodes.IFNONNULL, nonNullArg); + mv.visitLdcInsn(targetClass.getSimpleName()); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "cannotEncodeNull", + "(Ljava/lang/String;)Ljava/io/IOException;", + false); + mv.visitInsn(Opcodes.ATHROW); + mv.visitLabel(nonNullArg); + + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(targetClass)); + mv.visitVarInsn(Opcodes.ASTORE, 3); + + long constBytes = computeFixedConstBytes(specs, staticEncoding, hasNullableFields); + mv.visitLdcInsn(constBytes); + mv.visitVarInsn(Opcodes.LSTORE, 4); + if (hasNullableFields && !staticEncoding) { + mv.visitInsn(Opcodes.ICONST_M1); + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + + for (int pos = 0; pos < count; pos++) { + FieldSpec spec = specs[pos]; + switch (spec.kind) { + case PRIM_BYTE: + case PRIM_BOOL: + case PRIM_SHORT: + case PRIM_FLOAT: + case PRIM_DOUBLE: + break; + case PRIM_INT: + mv.visitVarInsn(Opcodes.LLOAD, 4); + emitReadMember(mv, 3, spec); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, VARINT_TYPE, "getLength", "(I)I", false); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 4); + break; + case PRIM_LONG: + mv.visitVarInsn(Opcodes.LLOAD, 4); + emitReadMember(mv, 3, spec); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, VARINT_TYPE, "getLength", "(J)I", false); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 4); + break; + default: + emitReadMember(mv, 3, spec); + mv.visitVarInsn(Opcodes.ASTORE, 7); + Label notNull = new Label(); + Label after = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitJumpInsn(Opcodes.IFNONNULL, notNull); + if (!spec.nullable) { + emitThrowNullNonNullable(mv, spec.rowIndex); + } else { + if (!staticEncoding) { + pushInt(mv, pos); + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + mv.visitJumpInsn(Opcodes.GOTO, after); + } + mv.visitLabel(notNull); + emitAddRefSize(mv, spec, 7, 4, 2); + mv.visitLabel(after); + break; + } + } + + if (hasNullableFields && !staticEncoding) { + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, WIRE_CODEC, "sizeOfNullMask", "(I)J", false); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 4); + } + + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, OBSERVER_TYPE, "update", "(Ljava/lang/Object;)V", false); + mv.visitInsn(Opcodes.RETURN); + return new ByteCodeAppender.Size(6, 8); + }; + } + + private static void addConstLong(MethodVisitor mv, int totalSlot, long delta) { + mv.visitVarInsn(Opcodes.LLOAD, totalSlot); + mv.visitLdcInsn(delta); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, totalSlot); + } + + private static void emitAddRefSize( + MethodVisitor mv, FieldSpec spec, int valSlot, int totalSlot, int obsSlot) { + switch (spec.kind) { + case BOX_BYTE: + case BOX_BOOL: + addConstLong(mv, totalSlot, 1L); + break; + case BOX_SHORT: + addConstLong(mv, totalSlot, 2L); + break; + case BOX_FLOAT: + addConstLong(mv, totalSlot, 4L); + break; + case BOX_DOUBLE: + case JODA_INSTANT: + case JODA_DATETIME: + addConstLong(mv, totalSlot, 8L); + break; + case BOX_INT: + mv.visitVarInsn(Opcodes.LLOAD, totalSlot); + mv.visitVarInsn(Opcodes.ALOAD, valSlot); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, VARINT_TYPE, "getLength", "(I)I", false); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, totalSlot); + break; + case BOX_LONG: + mv.visitVarInsn(Opcodes.LLOAD, totalSlot); + mv.visitVarInsn(Opcodes.ALOAD, valSlot); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J", false); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, VARINT_TYPE, "getLength", "(J)I", false); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, totalSlot); + break; + case ENUM_ORDINAL: + mv.visitVarInsn(Opcodes.LLOAD, totalSlot); + mv.visitVarInsn(Opcodes.ALOAD, valSlot); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Enum", "ordinal", "()I", false); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, VARINT_TYPE, "getLength", "(I)I", false); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, totalSlot); + break; + case STRING: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfString", "(Ljava/lang/String;)J"); + break; + case BYTES: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfBytes", "([B)J"); + break; + case DECIMAL: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfDecimal", "(Ljava/math/BigDecimal;)J"); + break; + case LOCAL_DATE: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfLocalDate", "(Ljava/time/LocalDate;)J"); + break; + case LOCAL_TIME: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfLocalTime", "(Ljava/time/LocalTime;)J"); + break; + case LOCAL_DATETIME: + emitAddStaticSize( + mv, totalSlot, valSlot, "sizeOfLocalDateTime", "(Ljava/time/LocalDateTime;)J"); + break; + case UUID_TYPE: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfUuid", "(Ljava/util/UUID;)J"); + break; + case NANOS_INSTANT: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfNanosInstant", "(Ljava/time/Instant;)J"); + break; + case MICROS_INSTANT: + emitAddStaticSize( + mv, totalSlot, valSlot, "sizeOfMicrosInstant", "(Ljava/time/Instant;)J"); + break; + case LIST_STRING: + emitAddObservedCollectionSize( + mv, totalSlot, valSlot, obsSlot, "observeStringCollectionByteSize"); + break; + case LIST_INT: + emitAddObservedCollectionSize( + mv, totalSlot, valSlot, obsSlot, "observeInt32CollectionByteSize"); + break; + case LIST_LONG: + emitAddObservedCollectionSize( + mv, totalSlot, valSlot, obsSlot, "observeInt64CollectionByteSize"); + break; + case LIST_DOUBLE: + emitAddObservedCollectionSize( + mv, totalSlot, valSlot, obsSlot, "observeDoubleCollectionByteSize"); + break; + case LIST_ROW: + mv.visitVarInsn(Opcodes.ALOAD, valSlot); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "subCoders", "[Lorg/apache/beam/sdk/coders/Coder;"); + pushInt(mv, spec.encPos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, obsSlot); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + GEN_TYPE, + "observeElementCollectionByteSize", + "(Ljava/util/Collection;Lorg/apache/beam/sdk/coders/Coder;" + OBSERVER_DESC + ")V", + false); + break; + case MAP_STRING_LONG: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfStringLongMap", "(Ljava/util/Map;)J"); + break; + case MAP_STRING_STRING: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfStringStringMap", "(Ljava/util/Map;)J"); + break; + case MAP_STRING_INT: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfStringIntMap", "(Ljava/util/Map;)J"); + break; + case MAP_STRING_DOUBLE: + emitAddStaticSize(mv, totalSlot, valSlot, "sizeOfStringDoubleMap", "(Ljava/util/Map;)J"); + break; + case SUB_ROW: + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn( + Opcodes.GETFIELD, BASE_TYPE, "subCoders", "[Lorg/apache/beam/sdk/coders/Coder;"); + pushInt(mv, spec.encPos); + mv.visitInsn(Opcodes.AALOAD); + mv.visitVarInsn(Opcodes.ALOAD, valSlot); + mv.visitVarInsn(Opcodes.ALOAD, obsSlot); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + CODER_TYPE, + "registerByteSizeObserver", + "(Ljava/lang/Object;" + OBSERVER_DESC + ")V", + false); + break; + default: + throw new AssertionError("Unexpected kind: " + spec.kind); + } + } + + private static void emitAddStaticSize( + MethodVisitor mv, int totalSlot, int valSlot, String method, String desc) { + mv.visitVarInsn(Opcodes.LLOAD, totalSlot); + mv.visitVarInsn(Opcodes.ALOAD, valSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, WIRE_CODEC, method, desc, false); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, totalSlot); + } + + private static void emitAddObservedCollectionSize( + MethodVisitor mv, int totalSlot, int valSlot, int obsSlot, String method) { + mv.visitVarInsn(Opcodes.LLOAD, totalSlot); + mv.visitVarInsn(Opcodes.ALOAD, valSlot); + mv.visitVarInsn(Opcodes.ALOAD, obsSlot); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + GEN_TYPE, + method, + "(Ljava/util/Collection;" + OBSERVER_DESC + ")J", + false); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, totalSlot); + } + } + + private static final class NullScanChunkImpl implements Implementation { + private final FieldSpec[] specs; + private final int start; + private final int end; + private final boolean storeBeanRefs; + private final int[] refSlotByPos; + + NullScanChunkImpl( + FieldSpec[] specs, int start, int end, boolean storeBeanRefs, int[] refSlotByPos) { + this.specs = specs; + this.start = start; + this.end = end; + this.storeBeanRefs = storeBeanRefs; + this.refSlotByPos = refSlotByPos; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + // POJO slots: 0=this, 1=obj, 2=chunkMask, 3=tempRef + // Bean slots: 0=this, 1=obj, 2=refs, 3=chunkMask, 4=tempRef + int maskSlot = storeBeanRefs ? 3 : 2; + int tempSlot = storeBeanRefs ? 4 : 3; + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ISTORE, maskSlot); + for (int pos = start; pos < end; pos++) { + FieldSpec spec = specs[pos]; + if (spec.kind.isPrimitive()) { + continue; + } + emitReadMember(mv, 1, spec); + mv.visitVarInsn(Opcodes.ASTORE, tempSlot); + if (storeBeanRefs) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + pushInt(mv, refSlotByPos[pos]); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitInsn(Opcodes.AASTORE); + } + Label notNull = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitJumpInsn(Opcodes.IFNONNULL, notNull); + if (!spec.nullable) { + emitThrowNullNonNullable(mv, spec.rowIndex); + } else { + mv.visitVarInsn(Opcodes.ILOAD, maskSlot); + pushInt(mv, 1 << (pos - start)); + mv.visitInsn(Opcodes.IOR); + mv.visitVarInsn(Opcodes.ISTORE, maskSlot); + } + mv.visitLabel(notNull); + } + mv.visitVarInsn(Opcodes.ILOAD, maskSlot); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(4, tempSlot + 1); + }; + } + } + + private static final class EncodeChunkImpl implements Implementation { + private final FieldSpec[] specs; + private final int start; + private final int end; + private final boolean useBeanRefs; + private final int[] refSlotByPos; + + EncodeChunkImpl( + FieldSpec[] specs, int start, int end, boolean useBeanRefs, int[] refSlotByPos) { + this.specs = specs; + this.start = start; + this.end = end; + this.useBeanRefs = useBeanRefs; + this.refSlotByPos = refSlotByPos; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + // Non-bean slots: 0=this, 1=obj, 2=out, 3=buf, 4=pos, 5=tempRef + // Bean slots: 0=this, 1=obj, 2=refs, 3=out, 4=buf, 5=pos, 6=tempRef + int outSlot = useBeanRefs ? 3 : 2; + int bufSlot = useBeanRefs ? 4 : 3; + int posSlot = useBeanRefs ? 5 : 4; + int tempSlot = useBeanRefs ? 6 : 5; + for (int pos = start; pos < end; pos++) { + FieldSpec spec = specs[pos]; + if (spec.kind.isPrimitive()) { + emitPackPrimitive(mv, spec, 1, outSlot, bufSlot, posSlot); + } else if (useBeanRefs) { + mv.visitVarInsn(Opcodes.ALOAD, 2); + pushInt(mv, refSlotByPos[pos]); + mv.visitInsn(Opcodes.AALOAD); + if (spec.javaType != Object.class) { + mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(spec.javaType)); + } + mv.visitVarInsn(Opcodes.ASTORE, tempSlot); + if (!spec.nullable) { + emitPackNonNullValue(mv, spec, tempSlot, outSlot, bufSlot, posSlot); + } else { + Label skip = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitJumpInsn(Opcodes.IFNULL, skip); + emitPackNonNullValue(mv, spec, tempSlot, outSlot, bufSlot, posSlot); + mv.visitLabel(skip); + } + } else { + emitReadMember(mv, 1, spec); + mv.visitVarInsn(Opcodes.ASTORE, tempSlot); + if (spec.nullable) { + Label skip = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitJumpInsn(Opcodes.IFNULL, skip); + emitPackNonNullValue(mv, spec, tempSlot, outSlot, bufSlot, posSlot); + mv.visitLabel(skip); + } else { + Label ok = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, tempSlot); + mv.visitJumpInsn(Opcodes.IFNONNULL, ok); + emitThrowNullNonNullable(mv, spec.rowIndex); + mv.visitLabel(ok); + emitPackNonNullValue(mv, spec, tempSlot, outSlot, bufSlot, posSlot); + } + } + } + mv.visitVarInsn(Opcodes.ILOAD, posSlot); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(8, tempSlot + 1); + }; + } + } + + private static final class ChunkedEncodeImpl implements Implementation { + private final Class targetClass; + private final int count; + private final int chunkCount; + private final boolean staticEncoding; + private final boolean hasNullableFields; + private final boolean isPojo; + private final int refCount; + private final boolean[] chunkHasRefs; + + ChunkedEncodeImpl( + Class targetClass, + int count, + int chunkCount, + boolean staticEncoding, + boolean hasNullableFields, + boolean isPojo, + int refCount, + boolean[] chunkHasRefs) { + this.targetClass = targetClass; + this.count = count; + this.chunkCount = chunkCount; + this.staticEncoding = staticEncoding; + this.hasNullableFields = hasNullableFields; + this.isPojo = isPojo; + this.refCount = refCount; + this.chunkHasRefs = chunkHasRefs; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + String ownerInternal = target.getInstrumentedType().getInternalName(); + String targetInternal = Type.getInternalName(targetClass); + String targetDesc = Type.getDescriptor(targetClass); + // Slots: 0=this, 1=rawValue, 2=out, 3=obj + emitNonNullArgCheck(mv, targetClass); + + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitTypeInsn(Opcodes.CHECKCAST, targetInternal); + mv.visitVarInsn(Opcodes.ASTORE, 3); + + boolean nullableHeader = hasNullableFields && !staticEncoding; + if (!nullableHeader) { + // Slots: 4=pool, 5=buf, 6=pos, 7=ex + String encDesc = "(" + targetDesc + OUT_DESC + "[BI)I"; + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 4); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 5); + + mv.visitLabel(tryStart); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ISTORE, 6); + if (!staticEncoding) { + pushInt(mv, count); + mv.visitInsn(Opcodes.LCONST_0); + emitPackCall(mv, "packHeader", "(IJ" + PACK_SUFFIX, 5, 6, 2); + } + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, ownerInternal, "encC" + c, encDesc, false); + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + emitFlush(mv, 5, 6, 2); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, 7); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(6, 8); + } + + // Nullable wide encode (single ScratchPool buffer + optional RefScratchPool for beans): + // Slots: 4=pool, 5=buf, 6=pos, 7=highestNullByteLen, 8=chunkMask + // If useRefs: 9=refPool, 10=refs, 11=ex; else 9=ex + boolean useRefs = !isPojo && refCount > 0; + int exSlot = useRefs ? 11 : 9; + // For MAX_CHUNKED_DIRECT_FIELDS <= 512, nullByteLen <= 64 < 128 -> always 1 byte. + int hdrLen = VarInt.getLength(count) + 1; + + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + Label tryRefStart = new Label(); + Label tryRefEnd = new Label(); + Label catchBufOnly = new Label(); + if (useRefs) { + mv.visitTryCatchBlock(tryRefStart, tryRefEnd, catchBufOnly, null); + } + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 4); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 5); + + if (useRefs) { + mv.visitLabel(tryRefStart); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + WIRE_CODEC, + "refScratchPool", + "()" + REF_SCRATCH_POOL_DESC, + false); + mv.visitVarInsn(Opcodes.ASTORE, 9); + mv.visitVarInsn(Opcodes.ALOAD, 9); + pushInt(mv, refCount); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, REF_SCRATCH_POOL, "acquire", "(I)[Ljava/lang/Object;", false); + mv.visitVarInsn(Opcodes.ASTORE, 10); + mv.visitLabel(tryRefEnd); + } + + mv.visitLabel(tryStart); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ISTORE, 7); + + String beanScanDesc = "(" + targetDesc + "[Ljava/lang/Object;)I"; + String pojoScanDesc = "(" + targetDesc + ")I"; + for (int c = 0; c < chunkCount; c++) { + if (chunkHasRefs[c]) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 3); + if (useRefs) { + mv.visitVarInsn(Opcodes.ALOAD, 10); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "nullScanBeanC" + c, beanScanDesc, false); + } else { + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "nullScanC" + c, pojoScanDesc, false); + } + mv.visitVarInsn(Opcodes.ISTORE, 8); + mv.visitVarInsn(Opcodes.ALOAD, 5); + pushInt(mv, hdrLen); + pushInt(mv, c); + mv.visitVarInsn(Opcodes.ILOAD, 8); + mv.visitVarInsn(Opcodes.ILOAD, 7); + } else { + mv.visitVarInsn(Opcodes.ALOAD, 5); + pushInt(mv, hdrLen); + pushInt(mv, c); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ILOAD, 7); + } + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "putChunkNullMask32", "([BIIII)I", false); + mv.visitVarInsn(Opcodes.ISTORE, 7); + } + + // Patch VarInt(count) + 1-byte nullByteLen in-place at buf[0..hdrLen). + mv.visitVarInsn(Opcodes.ALOAD, 5); + pushInt(mv, count); + mv.visitVarInsn(Opcodes.ILOAD, 7); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "patchWideNullHeaderPrefix", "([BII)I", false); + mv.visitVarInsn(Opcodes.ISTORE, 6); + + String beanEncDesc = "(" + targetDesc + "[Ljava/lang/Object;" + OUT_DESC + "[BI)I"; + String pojoEncDesc = "(" + targetDesc + OUT_DESC + "[BI)I"; + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 3); + if (useRefs && chunkHasRefs[c]) { + mv.visitVarInsn(Opcodes.ALOAD, 10); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "encBeanC" + c, beanEncDesc, false); + } else { + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "encC" + c, pojoEncDesc, false); + } + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + emitFlush(mv, 5, 6, 2); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + if (useRefs) { + mv.visitVarInsn(Opcodes.ALOAD, 9); + mv.visitVarInsn(Opcodes.ALOAD, 10); + pushInt(mv, refCount); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, REF_SCRATCH_POOL, "release", "([Ljava/lang/Object;I)V", false); + } + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, exSlot); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + if (useRefs) { + mv.visitVarInsn(Opcodes.ALOAD, 9); + mv.visitVarInsn(Opcodes.ALOAD, 10); + pushInt(mv, refCount); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, REF_SCRATCH_POOL, "release", "([Ljava/lang/Object;I)V", false); + } + mv.visitVarInsn(Opcodes.ALOAD, exSlot); + mv.visitInsn(Opcodes.ATHROW); + + if (useRefs) { + mv.visitLabel(catchBufOnly); + mv.visitVarInsn(Opcodes.ASTORE, exSlot); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, exSlot); + mv.visitInsn(Opcodes.ATHROW); + } + return new ByteCodeAppender.Size(7, exSlot + 1); + }; + } + } + + private static final class DecodeChunkImpl implements Implementation { + private final FieldSpec[] specs; + private final int start; + private final int end; + private final boolean nullable; + + DecodeChunkImpl(FieldSpec[] specs, int start, int end, boolean nullable) { + this.specs = specs; + this.start = start; + this.end = end; + this.nullable = nullable; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + // Instance slots: 0=this, 1=obj, 2=in, 3=buf [, 4=chunkMask] + if (nullable) { + for (int pos = start; pos < end; pos++) { + int bit = pos - start; + FieldSpec spec = specs[pos]; + Label isNull = new Label(); + Label after = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 4); + pushInt(mv, 1 << bit); + mv.visitInsn(Opcodes.IAND); + mv.visitJumpInsn(Opcodes.IFNE, isNull); + mv.visitVarInsn(Opcodes.ALOAD, 1); + emitReadValueForDecode(mv, spec, 2, 3); + emitWriteMember(mv, spec); + mv.visitJumpInsn(Opcodes.GOTO, after); + mv.visitLabel(isNull); + if (spec.kind.isPrimitive()) { + mv.visitLdcInsn(spec.schemaFieldName); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "nullPrimitive", + "(Ljava/lang/String;)Ljava/lang/NullPointerException;", + false); + mv.visitInsn(Opcodes.ATHROW); + } else { + // Explicitly write null to overwrite any non-null default field initializer in ctor. + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitInsn(Opcodes.ACONST_NULL); + emitWriteMember(mv, spec); + } + mv.visitLabel(after); + } + mv.visitInsn(Opcodes.RETURN); + return new ByteCodeAppender.Size(6, 5); + } + + for (int pos = start; pos < end; pos++) { + mv.visitVarInsn(Opcodes.ALOAD, 1); + emitReadValueForDecode(mv, specs[pos], 2, 3); + emitWriteMember(mv, specs[pos]); + } + mv.visitInsn(Opcodes.RETURN); + return new ByteCodeAppender.Size(6, 4); + }; + } + } + + private static final class ChunkedDecodeImpl implements Implementation { + private final Class targetClass; + private final int count; + private final int chunkCount; + private final boolean staticEncoding; + private final boolean hasNullableFields; + private final boolean needsScratch; + + ChunkedDecodeImpl( + Class targetClass, + int count, + int chunkCount, + boolean staticEncoding, + boolean hasNullableFields, + boolean needsScratch) { + this.targetClass = targetClass; + this.count = count; + this.chunkCount = chunkCount; + this.staticEncoding = staticEncoding; + this.hasNullableFields = hasNullableFields; + this.needsScratch = needsScratch; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + String ownerInternal = target.getInstrumentedType().getInternalName(); + String targetInternal = Type.getInternalName(targetClass); + String targetDesc = Type.getDescriptor(targetClass); + String noNullDesc = "(" + targetDesc + IN_DESC + "[B)V"; + String nullDesc = "(" + targetDesc + IN_DESC + "[BI)V"; + + if (staticEncoding) { + if (!needsScratch) { + // Slots: 0=this, 1=in, 2=res + emitNewTarget(mv, targetInternal, 2); + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitInsn(Opcodes.ACONST_NULL); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "decNoNullC" + c, noNullDesc, false); + } + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + return new ByteCodeAppender.Size(5, 3); + } + // Slots: 0=this, 1=in, 2=res, 3=pool, 4=buf, 5=ex + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchHandler = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 3); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 4); + + mv.visitLabel(tryStart); + emitNewTarget(mv, targetInternal, 2); + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "decNoNullC" + c, noNullDesc, false); + } + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(catchHandler); + mv.visitVarInsn(Opcodes.ASTORE, 5); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 4); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(6, 6); + } + + // Slots: 0=this, 1=in, 2=res, 3=streamFieldCount, 4=nullByteLen, 5=pool, 6=buf, + // 7=nullScratch, 8=nullBytes, 9=chunkMask, 10=ex + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + mv.visitVarInsn(Opcodes.ISTORE, 3); + + Label matchingCount = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 3); + pushInt(mv, count); + mv.visitJumpInsn(Opcodes.IF_ICMPEQ, matchingCount); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ILOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + BASE_TYPE, + "decodeEvolved", + "(I" + IN_DESC + ")Ljava/lang/Object;", + false); + mv.visitInsn(Opcodes.ARETURN); + mv.visitLabel(matchingCount); + + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readVarInt", "(" + IN_DESC + ")I", false); + mv.visitVarInsn(Opcodes.ISTORE, 4); + + Label badNullLen = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFLT, badNullLen); + + Label hasNulls = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitJumpInsn(Opcodes.IFNE, hasNulls); + + // nullByteLen == 0 fast path: skip ScratchPool completely when !needsScratch. + if (!needsScratch) { + emitNewTarget(mv, targetInternal, 2); + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitInsn(Opcodes.ACONST_NULL); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "decNoNullC" + c, noNullDesc, false); + } + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + } else { + Label tryStart0 = new Label(); + Label tryEnd0 = new Label(); + Label catch0 = new Label(); + mv.visitTryCatchBlock(tryStart0, tryEnd0, catch0, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 5); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 6); + + mv.visitLabel(tryStart0); + emitNewTarget(mv, targetInternal, 2); + for (int c = 0; c < chunkCount; c++) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "decNoNullC" + c, noNullDesc, false); + } + mv.visitLabel(tryEnd0); + + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(catch0); + mv.visitVarInsn(Opcodes.ASTORE, 10); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 10); + mv.visitInsn(Opcodes.ATHROW); + } + + mv.visitLabel(hasNulls); + if (!hasNullableFields) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ILOAD, 3); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, + BASE_TYPE, + "decodeEvolvedAfterNullLen", + "(II" + IN_DESC + ")Ljava/lang/Object;", + false); + mv.visitInsn(Opcodes.ARETURN); + } else { + Label tryStart1 = new Label(); + Label tryEnd1 = new Label(); + Label catch1 = new Label(); + Label tryBufAcqStart = new Label(); + Label tryBufAcqEnd = new Label(); + Label catchNullOnly = new Label(); + if (needsScratch) { + mv.visitTryCatchBlock(tryBufAcqStart, tryBufAcqEnd, catchNullOnly, null); + } + mv.visitTryCatchBlock(tryStart1, tryEnd1, catch1, null); + + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "scratchPool", "()" + SCRATCH_POOL_DESC, false); + mv.visitVarInsn(Opcodes.ASTORE, 5); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 7); + if (needsScratch) { + mv.visitLabel(tryBufAcqStart); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "acquire", "()[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 6); + mv.visitLabel(tryBufAcqEnd); + } else { + mv.visitInsn(Opcodes.ACONST_NULL); + mv.visitVarInsn(Opcodes.ASTORE, 6); + } + + mv.visitLabel(tryStart1); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "readNullBytes", "(" + IN_DESC + "I[B)[B", false); + mv.visitVarInsn(Opcodes.ASTORE, 8); + + emitNewTarget(mv, targetInternal, 2); + for (int c = 0; c < chunkCount; c++) { + Label chunkHasNulls = new Label(); + Label nextChunk = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 8); + mv.visitVarInsn(Opcodes.ILOAD, 4); + pushInt(mv, c); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, WIRE_CODEC, "extractChunkNullMask32", "([BII)I", false); + mv.visitVarInsn(Opcodes.ISTORE, 9); + mv.visitVarInsn(Opcodes.ILOAD, 9); + mv.visitJumpInsn(Opcodes.IFNE, chunkHasNulls); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "decNoNullC" + c, noNullDesc, false); + mv.visitJumpInsn(Opcodes.GOTO, nextChunk); + mv.visitLabel(chunkHasNulls); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitVarInsn(Opcodes.ILOAD, 9); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "decNullC" + c, nullDesc, false); + mv.visitLabel(nextChunk); + } + mv.visitLabel(tryEnd1); + + if (needsScratch) { + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + } + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitInsn(Opcodes.ARETURN); + + mv.visitLabel(catch1); + mv.visitVarInsn(Opcodes.ASTORE, 10); + if (needsScratch) { + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + } + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 10); + mv.visitInsn(Opcodes.ATHROW); + + if (needsScratch) { + mv.visitLabel(catchNullOnly); + mv.visitVarInsn(Opcodes.ASTORE, 10); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitVarInsn(Opcodes.ALOAD, 7); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, SCRATCH_POOL, "release", "([B)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 10); + mv.visitInsn(Opcodes.ATHROW); + } + } + + mv.visitLabel(badNullLen); + mv.visitVarInsn(Opcodes.ILOAD, 4); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + BASE_TYPE, + "invalidNullBitmapLength", + "(I)Ljava/io/IOException;", + false); + mv.visitInsn(Opcodes.ATHROW); + return new ByteCodeAppender.Size(8, 11); + }; + } + } + + private static final class IsCheapChunkImpl implements Implementation { + private final FieldSpec[] specs; + private final int start; + private final int end; + + IsCheapChunkImpl(FieldSpec[] specs, int start, int end) { + this.specs = specs; + this.start = start; + this.end = end; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + // Instance slots: 0=this, 1=obj, 2=tempRef + emitIsCheapRange(mv, specs, start, end, 1, 2); + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(4, 3); + }; + } + } + + private static final class ChunkedIsCheapImpl implements Implementation { + private final Class targetClass; + private final boolean[] chunkNeedsIsCheap; + private final boolean anyNeedsIsCheap; + + ChunkedIsCheapImpl(Class targetClass, boolean[] chunkNeedsIsCheap, boolean anyNeedsIsCheap) { + this.targetClass = targetClass; + this.chunkNeedsIsCheap = chunkNeedsIsCheap; + this.anyNeedsIsCheap = anyNeedsIsCheap; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + // Slots: 0=this, 1=rawValue [, 2=obj] + Label nonNull = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitJumpInsn(Opcodes.IFNONNULL, nonNull); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(nonNull); + + if (!anyNeedsIsCheap) { + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(2, 2); + } + + String ownerInternal = target.getInstrumentedType().getInternalName(); + String targetDesc = Type.getDescriptor(targetClass); + String chunkDesc = "(" + targetDesc + ")Z"; + + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(targetClass)); + mv.visitVarInsn(Opcodes.ASTORE, 2); + + for (int c = 0; c < chunkNeedsIsCheap.length; c++) { + if (!chunkNeedsIsCheap[c]) { + continue; + } + Label ok = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn( + Opcodes.INVOKESPECIAL, ownerInternal, "isCheapC" + c, chunkDesc, false); + mv.visitJumpInsn(Opcodes.IFNE, ok); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(ok); + } + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IRETURN); + return new ByteCodeAppender.Size(3, 3); + }; + } + } + + private static final class ByteSizeChunkImpl implements Implementation { + private final FieldSpec[] specs; + private final int start; + private final int end; + private final boolean trackNulls; + + ByteSizeChunkImpl(FieldSpec[] specs, int start, int end, boolean trackNulls) { + this.specs = specs; + this.start = start; + this.end = end; + this.trackNulls = trackNulls; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + // Instance slots: 0=this, 1=obj, 2=observer, 3..4=chunkBytes, 5=tempRef [, 6=localNullTag] + // When trackNulls is true, returns (chunkBytes << 6) | localNullTag where localNullTag is + // 0 (no null in chunk) or 1..32 ((pos - start) + 1), eliminating any heap allocation. + mv.visitInsn(Opcodes.LCONST_0); + mv.visitVarInsn(Opcodes.LSTORE, 3); + if (trackNulls) { + mv.visitInsn(Opcodes.ICONST_0); + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + for (int pos = start; pos < end; pos++) { + FieldSpec spec = specs[pos]; + switch (spec.kind) { + case PRIM_BYTE: + case PRIM_BOOL: + case PRIM_SHORT: + case PRIM_FLOAT: + case PRIM_DOUBLE: + break; + case PRIM_INT: + mv.visitVarInsn(Opcodes.LLOAD, 3); + emitReadMember(mv, 1, spec); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, VARINT_TYPE, "getLength", "(I)I", false); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 3); + break; + case PRIM_LONG: + mv.visitVarInsn(Opcodes.LLOAD, 3); + emitReadMember(mv, 1, spec); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, VARINT_TYPE, "getLength", "(J)I", false); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 3); + break; + default: + emitReadMember(mv, 1, spec); + mv.visitVarInsn(Opcodes.ASTORE, 5); + Label notNull = new Label(); + mv.visitVarInsn(Opcodes.ALOAD, 5); + mv.visitJumpInsn(Opcodes.IFNONNULL, notNull); + if (!spec.nullable) { + emitThrowNullNonNullable(mv, spec.rowIndex); + mv.visitLabel(notNull); + ByteSizeImpl.emitAddRefSize(mv, spec, 5, 3, 2); + } else { + Label after = new Label(); + if (trackNulls) { + pushInt(mv, (pos - start) + 1); + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + mv.visitJumpInsn(Opcodes.GOTO, after); + mv.visitLabel(notNull); + ByteSizeImpl.emitAddRefSize(mv, spec, 5, 3, 2); + mv.visitLabel(after); + } + break; + } + } + if (!trackNulls) { + mv.visitVarInsn(Opcodes.LLOAD, 3); + mv.visitInsn(Opcodes.LRETURN); + return new ByteCodeAppender.Size(6, 6); + } + + // Overflow guard: if chunkBytes >= (1L << 57), flush directly to observer before packing. + Label fits = new Label(); + mv.visitVarInsn(Opcodes.LLOAD, 3); + mv.visitLdcInsn(1L << 57); + mv.visitInsn(Opcodes.LCMP); + mv.visitJumpInsn(Opcodes.IFLT, fits); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.LLOAD, 3); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, OBSERVER_TYPE, "update", "(Ljava/lang/Object;)V", false); + mv.visitInsn(Opcodes.LCONST_0); + mv.visitVarInsn(Opcodes.LSTORE, 3); + mv.visitLabel(fits); + + mv.visitVarInsn(Opcodes.LLOAD, 3); + pushInt(mv, 6); + mv.visitInsn(Opcodes.LSHL); + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitInsn(Opcodes.I2L); + mv.visitInsn(Opcodes.LOR); + mv.visitInsn(Opcodes.LRETURN); + return new ByteCodeAppender.Size(6, 7); + }; + } + } + + private static final class ChunkedByteSizeImpl implements Implementation { + private final Class targetClass; + private final FieldSpec[] specs; + private final int chunkCount; + private final boolean staticEncoding; + private final boolean hasNullableFields; + private final boolean[] chunkNeedsByteSize; + private final boolean[] chunkHasNullable; + + ChunkedByteSizeImpl( + Class targetClass, + FieldSpec[] specs, + int chunkCount, + boolean staticEncoding, + boolean hasNullableFields, + boolean[] chunkNeedsByteSize, + boolean[] chunkHasNullable) { + this.targetClass = targetClass; + this.specs = specs; + this.chunkCount = chunkCount; + this.staticEncoding = staticEncoding; + this.hasNullableFields = hasNullableFields; + this.chunkNeedsByteSize = chunkNeedsByteSize; + this.chunkHasNullable = chunkHasNullable; + } + + @Override + public InstrumentedType prepare(InstrumentedType instrumentedType) { + return instrumentedType; + } + + @Override + public ByteCodeAppender appender(Target target) { + return (mv, context, method) -> { + String ownerInternal = target.getInstrumentedType().getInternalName(); + String targetDesc = Type.getDescriptor(targetClass); + String chunkDesc = "(" + targetDesc + OBSERVER_DESC + ")J"; + // Slots: 0=this, 1=rawValue, 2=observer, 3=obj, 4..5=total, 6=highestNull, + // 7..8=packed, 9=tag + emitNonNullArgCheck(mv, targetClass); + + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(targetClass)); + mv.visitVarInsn(Opcodes.ASTORE, 3); + + long constBytes = computeFixedConstBytes(specs, staticEncoding, hasNullableFields); + mv.visitLdcInsn(constBytes); + mv.visitVarInsn(Opcodes.LSTORE, 4); + + boolean trackNullsOverall = hasNullableFields && !staticEncoding; + if (trackNullsOverall) { + mv.visitInsn(Opcodes.ICONST_M1); + mv.visitVarInsn(Opcodes.ISTORE, 6); + } + + for (int c = 0; c < chunkCount; c++) { + if (!chunkNeedsByteSize[c]) { + continue; + } + if (trackNullsOverall && chunkHasNullable[c]) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, ownerInternal, "sizeC" + c, chunkDesc, false); + mv.visitVarInsn(Opcodes.LSTORE, 7); + + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitVarInsn(Opcodes.LLOAD, 7); + pushInt(mv, 6); + mv.visitInsn(Opcodes.LUSHR); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 4); + + mv.visitVarInsn(Opcodes.LLOAD, 7); + mv.visitLdcInsn(0x3FL); + mv.visitInsn(Opcodes.LAND); + mv.visitInsn(Opcodes.L2I); + mv.visitVarInsn(Opcodes.ISTORE, 9); + Label noChunkNull = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 9); + mv.visitJumpInsn(Opcodes.IFEQ, noChunkNull); + pushInt(mv, c * DIRECT_CHUNK_SIZE - 1); + mv.visitVarInsn(Opcodes.ILOAD, 9); + mv.visitInsn(Opcodes.IADD); + mv.visitVarInsn(Opcodes.ISTORE, 6); + mv.visitLabel(noChunkNull); + } else { + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 3); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, ownerInternal, "sizeC" + c, chunkDesc, false); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 4); + } + } + + if (trackNullsOverall) { + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitVarInsn(Opcodes.ILOAD, 6); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, WIRE_CODEC, "sizeOfNullMask", "(I)J", false); + mv.visitInsn(Opcodes.LADD); + mv.visitVarInsn(Opcodes.LSTORE, 4); + } + + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.LLOAD, 4); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); + mv.visitMethodInsn( + Opcodes.INVOKEVIRTUAL, OBSERVER_TYPE, "update", "(Ljava/lang/Object;)V", false); + mv.visitInsn(Opcodes.RETURN); + return new ByteCodeAppender.Size(6, 10); + }; + } + } +} diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java index 931a5cd62c7e..5c52b0a95461 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoder.java @@ -22,6 +22,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -36,6 +38,7 @@ import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptor; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; import org.checkerframework.checker.nullness.qual.Nullable; @@ -44,11 +47,30 @@ "nullness" // TODO(https://github.com/apache/beam/issues/20497) }) public class SchemaCoder extends CustomCoder { + private static final Coder NO_DIRECT_CODER = + new CustomCoder() { + @Override + public void encode(Object value, OutputStream outStream) { + throw new UnsupportedOperationException(); + } + + @Override + public Object decode(InputStream inStream) { + throw new UnsupportedOperationException(); + } + + @Override + public List> getCoderArguments() { + return Collections.emptyList(); + } + }; + protected final Schema schema; private final TypeDescriptor typeDescriptor; private final SerializableFunction toRowFunction; private final SerializableFunction fromRowFunction; private transient volatile @Nullable Coder delegateCoder; + private transient volatile @Nullable Coder directCoder; protected SchemaCoder( Schema schema, @@ -112,20 +134,53 @@ private Coder getDelegateCoder() { Coder coder = delegateCoder; if (coder == null) { // RowCoderGenerator caches based on id, so if a new instance of this RowCoder is - // deserialized, we don't need to run ByteBuddy again to construct the class. + // deserialized, we don't need to construct it again. coder = RowCoderGenerator.generate(schema); delegateCoder = coder; } return coder; } + @SuppressWarnings("unchecked") + private @Nullable Coder getDirectCoder() { + Coder coder = directCoder; + if (coder == null) { + if (Row.class.equals(typeDescriptor.getRawType()) + && SchemaUtils.isIdentityFunction(toRowFunction) + && SchemaUtils.isIdentityFunction(fromRowFunction)) { + coder = (Coder) getDelegateCoder(); + } else { + Coder generated = + DirectSchemaCoderGenerator.tryGenerate( + schema, typeDescriptor, toRowFunction, fromRowFunction); + coder = generated != null ? generated : (Coder) NO_DIRECT_CODER; + } + directCoder = coder; + } + return coder == NO_DIRECT_CODER ? null : coder; + } + + @VisibleForTesting + boolean hasDirectCoder() { + return getDirectCoder() instanceof DirectSchemaCoderGenerator.DirectSchemaCoderBase; + } + @Override public void encode(T value, OutputStream outStream) throws IOException { + Coder direct = getDirectCoder(); + if (direct != null) { + direct.encode(value, outStream); + return; + } getDelegateCoder().encode(toRowFunction.apply(value), outStream); } @Override public T decode(InputStream inStream) throws IOException { + Coder direct = getDirectCoder(); + if (direct != null) { + return direct.decode(inStream); + } return fromRowFunction.apply(getDelegateCoder().decode(inStream)); } @@ -134,11 +189,20 @@ public boolean isRegisterByteSizeObserverCheap(T value) { if (value == null) { return false; } + Coder direct = getDirectCoder(); + if (direct != null) { + return direct.isRegisterByteSizeObserverCheap(value); + } return getDelegateCoder().isRegisterByteSizeObserverCheap(toRowFunction.apply(value)); } @Override public void registerByteSizeObserver(T value, ElementByteSizeObserver observer) throws Exception { + Coder direct = getDirectCoder(); + if (direct != null) { + direct.registerByteSizeObserver(value, observer); + return; + } getDelegateCoder().registerByteSizeObserver(toRowFunction.apply(value), observer); } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/DirectSchemaCoderTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/DirectSchemaCoderTest.java new file mode 100644 index 000000000000..6fed19441e1c --- /dev/null +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/DirectSchemaCoderTest.java @@ -0,0 +1,4379 @@ +/* + * 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.beam.sdk.schemas; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nullable; +import org.apache.beam.sdk.coders.BigEndianShortCoder; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.CoderException; +import org.apache.beam.sdk.coders.IterableCoder; +import org.apache.beam.sdk.coders.RowCoder; +import org.apache.beam.sdk.coders.RowCoderGenerator; +import org.apache.beam.sdk.coders.RowWireCodec; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.annotations.DefaultSchema; +import org.apache.beam.sdk.schemas.logicaltypes.Date; +import org.apache.beam.sdk.schemas.logicaltypes.MicrosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.NanosDuration; +import org.apache.beam.sdk.schemas.logicaltypes.NanosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.OneOfType; +import org.apache.beam.sdk.schemas.logicaltypes.Time; +import org.apache.beam.sdk.schemas.logicaltypes.UuidLogicalType; +import org.apache.beam.sdk.util.BufferedElementCountingOutputStream; +import org.apache.beam.sdk.util.SerializableUtils; +import org.apache.beam.sdk.util.VarInt; +import org.apache.beam.sdk.util.common.ElementByteSizeObservableIterable; +import org.apache.beam.sdk.util.common.ElementByteSizeObservableIterator; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.TypeDescriptor; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests verifying bit-for-bit wire compatibility, byte-size observation, null handling, schema + * evolution, single-evaluation getters, and thread safety of {@link DirectSchemaCoderGenerator}, + * {@link RowWireCodec}, and unrolled {@link RowCoderGenerator}. + */ +@RunWith(JUnit4.class) +public class DirectSchemaCoderTest { + + public enum Status { + NEW, + ACTIVE, + CLOSED, + ARCHIVED + } + + @DefaultSchema(JavaFieldSchema.class) + public static class NestedItem { + public String label; + public int qty; + public double price; + + public NestedItem() {} + + public NestedItem(String label, int qty, double price) { + this.label = label; + this.qty = qty; + this.price = price; + } + + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof NestedItem)) { + return false; + } + NestedItem that = (NestedItem) o; + return qty == that.qty + && Double.compare(price, that.price) == 0 + && Objects.equals(label, that.label); + } + + @Override + public int hashCode() { + return Objects.hash(label, qty, price); + } + } + + @DefaultSchema(JavaFieldSchema.class) + public static class RichPojo { + public byte fByte; + public short fShort; + public int fInt; + public long fLong; + public float fFloat; + public double fDouble; + public boolean fBool; + public String fString; + public byte[] fBytes; + public BigDecimal fDecimal; + public Instant fInstant; + public LocalDate fDate; + public LocalTime fTime; + public LocalDateTime fDateTime; + public java.time.Instant fJavaInstant; + public UUID fUuid; + public Status fEnum; + public List fStrList; + public List fIntList; + public List fLongList; + public List fDoubleList; + public List fNestedList; + public Map fStrLongMap; + public Map fStrStrMap; + public Map fStrIntMap; + public Map fStrDblMap; + public NestedItem fNested; + + public RichPojo() {} + + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof RichPojo)) { + return false; + } + RichPojo r = (RichPojo) o; + return fByte == r.fByte + && fShort == r.fShort + && fInt == r.fInt + && fLong == r.fLong + && Float.floatToIntBits(fFloat) == Float.floatToIntBits(r.fFloat) + && Double.doubleToLongBits(fDouble) == Double.doubleToLongBits(r.fDouble) + && fBool == r.fBool + && Objects.equals(fString, r.fString) + && Arrays.equals(fBytes, r.fBytes) + && Objects.equals(fDecimal, r.fDecimal) + && Objects.equals(fInstant, r.fInstant) + && Objects.equals(fDate, r.fDate) + && Objects.equals(fTime, r.fTime) + && Objects.equals(fDateTime, r.fDateTime) + && Objects.equals(fJavaInstant, r.fJavaInstant) + && Objects.equals(fUuid, r.fUuid) + && fEnum == r.fEnum + && Objects.equals(fStrList, r.fStrList) + && Objects.equals(fIntList, r.fIntList) + && Objects.equals(fLongList, r.fLongList) + && Objects.equals(fDoubleList, r.fDoubleList) + && Objects.equals(fNestedList, r.fNestedList) + && Objects.equals(fStrLongMap, r.fStrLongMap) + && Objects.equals(fStrStrMap, r.fStrStrMap) + && Objects.equals(fStrIntMap, r.fStrIntMap) + && Objects.equals(fStrDblMap, r.fStrDblMap) + && Objects.equals(fNested, r.fNested); + } + + @Override + public int hashCode() { + return Objects.hash(fInt, fLong, fString, fUuid); + } + } + + @DefaultSchema(JavaFieldSchema.class) + public static class NullableWithDefaultsPojo { + public long requiredId; + public @Nullable String optStr = "non-null-default"; + public @Nullable Integer optInt = 777; + public @Nullable Long optLong = 888L; + public @Nullable Double optDouble = 1.25; + public @Nullable Boolean optBool = Boolean.TRUE; + public @Nullable UUID optUuid = new UUID(1L, 2L); + public @Nullable Status optStatus = Status.ACTIVE; + public @Nullable NestedItem optNested = new NestedItem("init", 1, 1.0); + public @Nullable List optList = Collections.singletonList("init"); + public @Nullable Map optMap = Collections.singletonMap("init", 1L); + + public NullableWithDefaultsPojo() {} + + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof NullableWithDefaultsPojo)) { + return false; + } + NullableWithDefaultsPojo that = (NullableWithDefaultsPojo) o; + return requiredId == that.requiredId + && Objects.equals(optStr, that.optStr) + && Objects.equals(optInt, that.optInt) + && Objects.equals(optLong, that.optLong) + && Objects.equals(optDouble, that.optDouble) + && Objects.equals(optBool, that.optBool) + && Objects.equals(optUuid, that.optUuid) + && optStatus == that.optStatus + && Objects.equals(optNested, that.optNested) + && Objects.equals(optList, that.optList) + && Objects.equals(optMap, that.optMap); + } + + @Override + public int hashCode() { + return Objects.hash(requiredId, optStr, optInt); + } + } + + @DefaultSchema(JavaBeanSchema.class) + public static class FluentCountingBean { + private int id; + private @Nullable String name = "default-name"; + private @Nullable Long count; + private List tags = new ArrayList<>(); + private Map metrics = new HashMap<>(); + final transient AtomicInteger nameGetterCalls = new AtomicInteger(); + + public int getId() { + return id; + } + + public FluentCountingBean setId(int id) { + this.id = id; + return this; + } + + public @Nullable String getName() { + nameGetterCalls.incrementAndGet(); + return name; + } + + public FluentCountingBean setName(@Nullable String name) { + this.name = name; + return this; + } + + public @Nullable Long getCount() { + return count; + } + + public void setCount(@Nullable Long count) { + this.count = count; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Map getMetrics() { + return metrics; + } + + public void setMetrics(Map metrics) { + this.metrics = metrics; + } + + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof FluentCountingBean)) { + return false; + } + FluentCountingBean that = (FluentCountingBean) o; + return id == that.id + && Objects.equals(name, that.name) + && Objects.equals(count, that.count) + && Objects.equals(tags, that.tags) + && Objects.equals(metrics, that.metrics); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, count); + } + } + + @DefaultSchema(JavaFieldSchema.class) + public static class SmallPojoV2 { + public @Nullable Integer a; + public @Nullable String b; + public @Nullable Long c; + + public SmallPojoV2() {} + } + + @DefaultSchema(JavaFieldSchema.class) + public static class OrderedPojo { + public String alpha; + public int beta; + public @Nullable String gamma; + public long delta; + + public OrderedPojo() {} + } + + private static byte[] encode(Coder coder, Object value) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + coder.encode(value, out); + return out.toByteArray(); + } + + private static long observeSize(Coder coder, Object value) throws Exception { + final long[] total = {0L}; + ElementByteSizeObserver obs = + new ElementByteSizeObserver() { + @Override + protected void reportElementSize(long elementSize) { + total[0] += elementSize; + } + }; + coder.registerByteSizeObserver(value, obs); + obs.advance(); + return total[0]; + } + + private static RichPojo sampleRichPojo(String s, BigDecimal dec, int i, long l) { + RichPojo p = new RichPojo(); + p.fByte = (byte) -42; + p.fShort = (short) -12345; + p.fInt = i; + p.fLong = l; + p.fFloat = Float.NaN; + p.fDouble = -0.0; + p.fBool = true; + p.fString = s; + p.fBytes = new byte[] {0, 1, -1, 127, -128}; + p.fDecimal = dec; + p.fInstant = Instant.ofEpochMilli(1_700_000_000_123L); + p.fDate = LocalDate.of(2026, 11, 25); + p.fTime = LocalTime.of(23, 59, 58, 123_456_789); + p.fDateTime = LocalDateTime.of(1999, 12, 31, 12, 30, 45, 500); + p.fJavaInstant = java.time.Instant.ofEpochSecond(-12345L, 987_654_321); + p.fUuid = new UUID(0xFEDCBA9876543210L, 0x0123456789ABCDEFL); + p.fEnum = Status.ARCHIVED; + p.fStrList = Arrays.asList("", "ascii", "cafรฉ", "๐Ÿš€"); + p.fIntList = Arrays.asList(Integer.MIN_VALUE, -1, 0, 127, 128, Integer.MAX_VALUE); + p.fLongList = Arrays.asList(Long.MIN_VALUE, -1L, 0L, 127L, 128L, Long.MAX_VALUE); + p.fDoubleList = Arrays.asList(-0.0, 0.0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); + p.fNestedList = Arrays.asList(new NestedItem("a", 1, 2.5), new NestedItem("bรฉ", -3, 0.0)); + p.fStrLongMap = new LinkedHashMap<>(); + p.fStrLongMap.put("k1", -1L); + p.fStrLongMap.put("clรฉ", Long.MAX_VALUE); + p.fStrStrMap = new LinkedHashMap<>(); + p.fStrStrMap.put("a", ""); + p.fStrStrMap.put("b", "val-๐Ÿš€"); + p.fStrIntMap = new LinkedHashMap<>(); + p.fStrIntMap.put("x", -100); + p.fStrDblMap = new LinkedHashMap<>(); + p.fStrDblMap.put("pi", Math.PI); + p.fNested = new NestedItem("Seattle", 98101, 47.6062); + return p; + } + + private static String repeatChar(char c, int count) { + char[] chars = new char[count]; + Arrays.fill(chars, c); + return new String(chars); + } + + @Test + public void testRichPojoWireIdentityWithRowCoder() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(RichPojo.class); + assertTrue("Expected DirectSchemaCoder for RichPojo", coder.hasDirectCoder()); + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + + RichPojo[] cases = + new RichPojo[] { + sampleRichPojo("", BigDecimal.ZERO, 0, 0L), + sampleRichPojo(repeatChar('a', 127), new BigDecimal("127"), 127, 127L), + sampleRichPojo(repeatChar('b', 128), new BigDecimal("128"), 128, 128L), + sampleRichPojo(repeatChar('c', 253), new BigDecimal("-128"), -1, -1L), + sampleRichPojo( + repeatChar('d', 254), new BigDecimal("-129"), Integer.MIN_VALUE, Long.MIN_VALUE), + sampleRichPojo(repeatChar('e', 255), new BigDecimal("32767"), 16383, Long.MAX_VALUE), + sampleRichPojo(repeatChar('f', 512), new BigDecimal("-32769"), 16384, -999_999_999_999L), + sampleRichPojo( + "hello cafรฉ ๆ—ฅๆœฌ่ชž ๐Ÿš€", new BigDecimal(BigInteger.valueOf(Long.MAX_VALUE), 5), -42, 42L), + sampleRichPojo( + "abc\uD800xyz", // unpaired high surrogate inside ASCII string + new BigDecimal("1234567890123456789012345678901234567890.99"), + Integer.MAX_VALUE, + 1L), + sampleRichPojo("min-long", new BigDecimal(BigInteger.valueOf(Long.MIN_VALUE), -3), 0, 0L), + }; + + for (RichPojo p : cases) { + byte[] directBytes = encode(coder, p); + Row asRow = coder.getToRowFunction().apply(p); + byte[] rowBytes = encode(rowCoder, asRow); + assertArrayEquals("Wire mismatch for string=" + p.fString, rowBytes, directBytes); + + RichPojo decoded = coder.decode(new ByteArrayInputStream(directBytes)); + RichPojo expectedPojo = p; + if (p.fString.indexOf('\uD800') >= 0) { + // UTF-8 encoding replaces unpaired surrogates with U+FFFD identically to StringUtf8Coder. + expectedPojo = + coder.getFromRowFunction().apply(rowCoder.decode(new ByteArrayInputStream(rowBytes))); + assertEquals("abc?xyz", decoded.fString); + } + assertEquals(expectedPojo, decoded); + + // Cross-decode: RowCoder bytes -> DirectSchemaCoder and DirectSchemaCoder bytes -> RowCoder. + RichPojo fromRowBytes = coder.decode(new ByteArrayInputStream(rowBytes)); + assertEquals(expectedPojo, fromRowBytes); + Row rowDecoded = rowCoder.decode(new ByteArrayInputStream(directBytes)); + assertEquals(expectedPojo, coder.getFromRowFunction().apply(rowDecoded)); + + assertEquals(directBytes.length, observeSize(coder, p)); + assertEquals(rowBytes.length, observeSize(rowCoder, asRow)); + } + + // Empty lists & maps. + RichPojo empty = sampleRichPojo("", BigDecimal.ONE, 1, 1L); + empty.fBytes = new byte[0]; + empty.fStrList = Collections.emptyList(); + empty.fIntList = Collections.emptyList(); + empty.fLongList = Collections.emptyList(); + empty.fDoubleList = Collections.emptyList(); + empty.fNestedList = Collections.emptyList(); + empty.fStrLongMap = Collections.emptyMap(); + empty.fStrStrMap = Collections.emptyMap(); + empty.fStrIntMap = Collections.emptyMap(); + empty.fStrDblMap = Collections.emptyMap(); + byte[] directEmpty = encode(coder, empty); + byte[] rowEmpty = encode(rowCoder, coder.getToRowFunction().apply(empty)); + assertArrayEquals(rowEmpty, directEmpty); + assertEquals(empty, coder.decode(new ByteArrayInputStream(directEmpty))); + assertEquals(directEmpty.length, observeSize(coder, empty)); + } + + @Test + public void testNullablePojoOverwritesConstructorDefaults() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = + registry.getSchemaCoder(NullableWithDefaultsPojo.class); + assertTrue("Expected DirectSchemaCoder", coder.hasDirectCoder()); + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + + NullableWithDefaultsPojo allNulls = new NullableWithDefaultsPojo(); + allNulls.requiredId = 42L; + allNulls.optStr = null; + allNulls.optInt = null; + allNulls.optLong = null; + allNulls.optDouble = null; + allNulls.optBool = null; + allNulls.optUuid = null; + allNulls.optStatus = null; + allNulls.optNested = null; + allNulls.optList = null; + allNulls.optMap = null; + + byte[] directBytes = encode(coder, allNulls); + byte[] rowBytes = encode(rowCoder, coder.getToRowFunction().apply(allNulls)); + assertArrayEquals(rowBytes, directBytes); + assertEquals(directBytes.length, observeSize(coder, allNulls)); + + NullableWithDefaultsPojo decoded = coder.decode(new ByteArrayInputStream(directBytes)); + assertEquals(42L, decoded.requiredId); + assertNull(decoded.optStr); + assertNull(decoded.optInt); + assertNull(decoded.optLong); + assertNull(decoded.optDouble); + assertNull(decoded.optBool); + assertNull(decoded.optUuid); + assertNull(decoded.optStatus); + assertNull(decoded.optNested); + assertNull(decoded.optList); + assertNull(decoded.optMap); + assertEquals(allNulls, decoded); + + // Sparse nulls & zero nulls. + NullableWithDefaultsPojo nonNull = new NullableWithDefaultsPojo(); + nonNull.requiredId = -9L; + byte[] nonNullBytes = encode(coder, nonNull); + assertArrayEquals(encode(rowCoder, coder.getToRowFunction().apply(nonNull)), nonNullBytes); + assertEquals(nonNull, coder.decode(new ByteArrayInputStream(nonNullBytes))); + assertEquals(nonNullBytes.length, observeSize(coder, nonNull)); + } + + @Test + public void testFluentJavaBeanAndSingleGetterInvocation() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(FluentCountingBean.class); + assertTrue("Expected DirectSchemaCoder for JavaBean", coder.hasDirectCoder()); + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + + FluentCountingBean bean = new FluentCountingBean().setId(7).setName("hello"); + bean.setCount(null); + bean.setTags(Arrays.asList("x", "y")); + bean.setMetrics(ImmutableMap.of("m1", 10L)); + + bean.nameGetterCalls.set(0); + byte[] directBytes = encode(coder, bean); + assertEquals( + "Nullable JavaBean getter must be invoked exactly once", 1, bean.nameGetterCalls.get()); + + byte[] rowBytes = encode(rowCoder, coder.getToRowFunction().apply(bean)); + assertArrayEquals(rowBytes, directBytes); + assertEquals(directBytes.length, observeSize(coder, bean)); + + FluentCountingBean decoded = coder.decode(new ByteArrayInputStream(directBytes)); + assertEquals(bean, decoded); + assertNull(decoded.getCount()); + + // Now test null name overwrites "default-name" constructor initializer. + bean.setName(null); + bean.setCount(99L); + bean.nameGetterCalls.set(0); + byte[] nullNameBytes = encode(coder, bean); + assertEquals(1, bean.nameGetterCalls.get()); + FluentCountingBean decodedNull = coder.decode(new ByteArrayInputStream(nullNameBytes)); + assertNull(decodedNull.getName()); + assertEquals(Long.valueOf(99L), decodedNull.getCount()); + assertEquals(nullNameBytes.length, observeSize(coder, bean)); + } + + @Test + public void testStaticEncodingAndEncodingPositionOverride() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + Schema baseSchema = registry.getSchema(OrderedPojo.class); + UUID uuid = UUID.randomUUID(); + Schema reordered = + Schema.builder() + .addStringField("alpha") + .addInt32Field("beta") + .addNullableStringField("gamma") + .addInt64Field("delta") + .build(); + reordered.setUUID(uuid); + RowCoder.overrideEncodingPositions( + uuid, ImmutableMap.of("delta", 0, "gamma", 1, "alpha", 2, "beta", 3)); + + JavaFieldSchema provider = new JavaFieldSchema(); + SchemaCoder coder = + SchemaCoder.of( + reordered, + org.apache.beam.sdk.values.TypeDescriptor.of(OrderedPojo.class), + provider + .new ToRowWithValueGetters<>( + reordered, org.apache.beam.sdk.values.TypeDescriptor.of(OrderedPojo.class)), + provider.fromRowFunction(TypeDescriptor.of(OrderedPojo.class))); + assertNotNull(baseSchema); + + // Also test direct static_encoding with NestedItem. + Schema staticSchema = + Schema.builder() + .addStringField("label") + .addInt32Field("qty") + .addDoubleField("price") + .setOptions( + Schema.Options.builder() + .setOption("beam:option:row:static_encoding", FieldType.BOOLEAN, true) + .build()) + .build(); + SchemaCoder staticCoder = + SchemaCoder.of( + staticSchema, + org.apache.beam.sdk.values.TypeDescriptor.of(NestedItem.class), + provider + .new ToRowWithValueGetters<>( + staticSchema, org.apache.beam.sdk.values.TypeDescriptor.of(NestedItem.class)), + provider.fromRowFunction(TypeDescriptor.of(NestedItem.class))); + assertTrue("Expected DirectSchemaCoder for static encoding", staticCoder.hasDirectCoder()); + NestedItem item = new NestedItem("apple", 5, 1.5); + byte[] directStatic = encode(staticCoder, item); + byte[] rowStatic = + encode(RowCoder.of(staticSchema), staticCoder.getToRowFunction().apply(item)); + assertArrayEquals(rowStatic, directStatic); + assertEquals(item, staticCoder.decode(new ByteArrayInputStream(directStatic))); + assertEquals(directStatic.length, observeSize(staticCoder, item)); + + // Verify overrideEncodingPositions bytes match RowCoder for reordered schema. + OrderedPojo op = new OrderedPojo(); + op.alpha = "hi"; + op.beta = 42; + op.gamma = null; + op.delta = 999L; + byte[] directReordered = encode(coder, op); + byte[] rowReordered = encode(RowCoder.of(reordered), coder.getToRowFunction().apply(op)); + assertArrayEquals(rowReordered, directReordered); + assertTrue(coder.hasDirectCoder()); + OrderedPojo decOp = coder.decode(new ByteArrayInputStream(directReordered)); + assertEquals("hi", decOp.alpha); + assertEquals(42, decOp.beta); + assertNull(decOp.gamma); + assertEquals(999L, decOp.delta); + assertEquals(directReordered.length, observeSize(coder, op)); + } + + @Test + public void testWideRowCoderOver64FieldsAndBigDecimalBoundaries() throws Exception { + Schema.Builder sb = Schema.builder(); + Object[] vals = new Object[70]; + for (int i = 0; i < 70; i++) { + sb.addNullableInt32Field("f_" + i); + vals[i] = (i % 7 == 0) ? null : (i * -13); + } + Schema wide = sb.build(); + RowCoder wideCoder = RowCoder.of(wide); + Row row = Row.withSchema(wide).addValues(vals).build(); + byte[] bytes = encode(wideCoder, row); + assertEquals(row, wideCoder.decode(new ByteArrayInputStream(bytes))); + assertEquals(bytes.length, observeSize(wideCoder, row)); + + // Also test BigDecimal boundaries bit-for-bit against BigDecimalCoder. + BigDecimal[] decimals = { + BigDecimal.ZERO, + new BigDecimal("0.00"), + BigDecimal.ONE, + new BigDecimal("-1"), + new BigDecimal("127"), + new BigDecimal("128"), + new BigDecimal("-128"), + new BigDecimal("-129"), + new BigDecimal("32767"), + new BigDecimal("32768"), + new BigDecimal("-32768"), + new BigDecimal("-32769"), + BigDecimal.valueOf(Long.MAX_VALUE, 10), + BigDecimal.valueOf(Long.MIN_VALUE, -5), + new BigDecimal(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE), 2), + new BigDecimal(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE), 2), + }; + org.apache.beam.sdk.coders.BigDecimalCoder refCoder = + org.apache.beam.sdk.coders.BigDecimalCoder.of(); + byte[] scratch = new byte[256]; + for (BigDecimal bd : decimals) { + ByteArrayOutputStream actual = new ByteArrayOutputStream(); + int pos = RowWireCodec.packDecimal(bd, scratch, 0, actual); + RowWireCodec.flush(scratch, pos, actual); + byte[] expected = encode(refCoder, bd); + assertArrayEquals("BigDecimal wire mismatch for " + bd, expected, actual.toByteArray()); + assertEquals(bd, RowWireCodec.readDecimal(new ByteArrayInputStream(expected), scratch)); + assertEquals(expected.length, RowWireCodec.sizeOfDecimal(bd)); + } + } + + @Test + public void testSchemaEvolutionAndOversizedNullBitmap() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coderV2 = registry.getSchemaCoder(SmallPojoV2.class); + assertTrue(coderV2.hasDirectCoder()); + + // Write a 2-field stream (older schema missing field 'c'). + Schema v1Schema = + Schema.builder().addNullableInt32Field("a").addNullableStringField("b").build(); + Row v1Row = Row.withSchema(v1Schema).addValues(123, "old").build(); + byte[] v1Bytes = encode(RowCoder.of(v1Schema), v1Row); + + SmallPojoV2 decoded = coderV2.decode(new ByteArrayInputStream(v1Bytes)); + assertEquals(Integer.valueOf(123), decoded.a); + assertEquals("old", decoded.b); + assertNull(decoded.c); + + // Oversized null bitmap (10 bytes all zero except bit 1 => 'b' is null). + ByteArrayOutputStream padded = new ByteArrayOutputStream(); + VarInt.encode(3, padded); + VarInt.encode(10, padded); + byte[] nullBytes = new byte[10]; + nullBytes[0] = 0x02; // field 1 ('b') is null + padded.write(nullBytes); + VarInt.encode(77, padded); // a = 77 + VarInt.encode(555L, padded); // c = 555 + SmallPojoV2 decodedPadded = coderV2.decode(new ByteArrayInputStream(padded.toByteArray())); + assertEquals(Integer.valueOf(77), decodedPadded.a); + assertNull(decodedPadded.b); + assertEquals(Long.valueOf(555L), decodedPadded.c); + } + + @Test + public void testChunkedUnknownSizeIterableDecoding() throws Exception { + byte[] scratch = new byte[256]; + // Emit a ListCoder stream using unknown-size (-1) chunked framing. + ByteArrayOutputStream strStream = new ByteArrayOutputStream(); + strStream.write(new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}); + BufferedElementCountingOutputStream counting = + new BufferedElementCountingOutputStream(strStream); + for (String s : Arrays.asList("one", "two", "three")) { + counting.markElementStart(); + StringUtf8Coder.of().encode(s, counting); + } + counting.finish(); + assertEquals( + Arrays.asList("one", "two", "three"), + RowWireCodec.readStringList(new ByteArrayInputStream(strStream.toByteArray()), scratch)); + + // Ensure IterableCoder reference gives the exact same bytes. + Iterable nonCollection = () -> Arrays.asList(10, -20, 30).iterator(); + ByteArrayOutputStream intStream = new ByteArrayOutputStream(); + IterableCoder.of(VarIntCoder.of()).encode(nonCollection, intStream); + assertEquals( + Arrays.asList(10, -20, 30), + RowWireCodec.readInt32List(new ByteArrayInputStream(intStream.toByteArray()), scratch)); + } + + @Test + public void testErrorCasesAndSerialization() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(NestedItem.class); + assertTrue(coder.hasDirectCoder()); + + // Round-trip Java serialization of SchemaCoder clears transient directCoder & restores + // seamlessly. + SchemaCoder cloned = SerializableUtils.clone(coder); + assertEquals(coder, cloned); + assertEquals(coder.hashCode(), cloned.hashCode()); + NestedItem item = new NestedItem("box", 3, 9.99); + byte[] bytes = encode(cloned, item); + assertEquals(item, cloned.decode(new ByteArrayInputStream(bytes))); + assertTrue(cloned.hasDirectCoder()); + + // Null top-level value throws CoderException. + assertThrows(CoderException.class, () -> coder.encode(null, new ByteArrayOutputStream())); + + // Null in non-nullable field throws RuntimeException matching RowWithGetters. + NestedItem nullLabel = new NestedItem(null, 1, 2.0); + RuntimeException ex = + assertThrows( + RuntimeException.class, () -> coder.encode(nullLabel, new ByteArrayOutputStream())); + assertTrue(ex.getMessage().contains("Null value set on non-nullable field")); + + // Truncated stream throws CoderException / IOException. + byte[] truncated = Arrays.copyOf(bytes, bytes.length - 2); + assertThrows(IOException.class, () -> coder.decode(new ByteArrayInputStream(truncated))); + + // Empty collection vs null-element checks. + assertFalse(coder.isRegisterByteSizeObserverCheap(null)); + assertTrue(coder.isRegisterByteSizeObserverCheap(item)); + NestedItem longStr = new NestedItem(repeatChar('z', 2000), 1, 2.0); + assertFalse(coder.isRegisterByteSizeObserverCheap(longStr)); + + // Invalid enum ordinal check. + assertThrows( + IllegalArgumentException.class, + () -> DirectSchemaCoderGenerator.enumConstantForOrdinal(Status.class, -1)); + assertThrows( + IllegalArgumentException.class, + () -> DirectSchemaCoderGenerator.enumConstantForOrdinal(Status.class, 99)); + + // Null elements inside non-nullable list/map throw CoderException identically. + byte[] scratch = new byte[256]; + assertThrows( + CoderException.class, + () -> + RowWireCodec.packStringCollection( + Arrays.asList("ok", null), scratch, 0, new ByteArrayOutputStream())); + Map nullValMap = new HashMap<>(); + nullValMap.put("k", null); + assertThrows( + CoderException.class, + () -> RowWireCodec.packStringLongMap(nullValMap, scratch, 0, new ByteArrayOutputStream())); + } + + @Test + public void testLogicalTypeZeroRoundTripIdentityInRowAndCreator() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(RichPojo.class); + RichPojo original = sampleRichPojo("id-test", BigDecimal.TEN, 1, 2L); + + // toRow (RowWithGetters) passes exact immutable logical-type references straight through. + Row lazyRow = coder.getToRowFunction().apply(original); + assertSame(original.fUuid, lazyRow.getLogicalTypeValue("fUuid", UUID.class)); + assertSame(original.fDate, lazyRow.getLogicalTypeValue("fDate", LocalDate.class)); + assertSame(original.fTime, lazyRow.getLogicalTypeValue("fTime", LocalTime.class)); + assertSame(original.fDateTime, lazyRow.getLogicalTypeValue("fDateTime", LocalDateTime.class)); + assertSame( + original.fJavaInstant, + lazyRow.getLogicalTypeValue("fJavaInstant", java.time.Instant.class)); + + // Materialize a RowWithStorage holding those exact references and verify FromRowUsingCreator + // avoids converting toBaseType -> toInputType. + Object[] materialized = new Object[coder.getSchema().getFieldCount()]; + for (int i = 0; i < materialized.length; i++) { + materialized[i] = lazyRow.getValue(i); + } + Row storageRow = Row.attachValues(coder.getSchema(), materialized); + RichPojo recreated = coder.getFromRowFunction().apply(storageRow); + assertSame(original.fUuid, recreated.fUuid); + assertSame(original.fDate, recreated.fDate); + assertSame(original.fTime, recreated.fTime); + assertSame(original.fDateTime, recreated.fDateTime); + assertSame(original.fJavaInstant, recreated.fJavaInstant); + } + + private static List nonRandomAccessList(Object... values) { + return new AbstractList() { + @Override + public Object get(int index) { + return values[index]; + } + + @Override + public int size() { + return values.length; + } + }; + } + + @Test + public void testRowFieldCodecActiveAndStorageVariantsWireIdentical() throws Exception { + Schema nonNullSchema = + Schema.builder() + .addInt32Field("a") + .addInt64Field("b") + .addDoubleField("c") + .addStringField("d") + .build(); + RowCoder nonNullCoder = RowCoder.of(nonNullSchema); + assertTrue( + "Expected generated RowFieldCodec for nonNullSchema", + RowCoderGenerator.hasGeneratedFieldCodec(RowCoderGenerator.generate(nonNullSchema))); + + Object[] vals = new Object[] {42, 9_876_543_210L, 3.14, "hello"}; + Row builderRow = Row.withSchema(nonNullSchema).addValues(vals).build(); + Row arrayRow = Row.attachValues(nonNullSchema, vals); + Row nonRaRow = Row.attachValues(nonNullSchema, nonRandomAccessList(vals)); + byte[] builderBytes = encode(nonNullCoder, builderRow); + assertArrayEquals(builderBytes, encode(nonNullCoder, arrayRow)); + assertArrayEquals(builderBytes, encode(nonNullCoder, nonRaRow)); + assertEquals(builderRow, nonNullCoder.decode(new ByteArrayInputStream(builderBytes))); + + Schema nullableSchema = + Schema.builder() + .addInt32Field("a") + .addNullableStringField("b") + .addNullableInt64Field("c") + .addDoubleField("d") + .build(); + RowCoder nullableCoder = RowCoder.of(nullableSchema); + assertTrue( + "Expected generated RowFieldCodec for nullableSchema", + RowCoderGenerator.hasGeneratedFieldCodec(RowCoderGenerator.generate(nullableSchema))); + + Object[] nullableVals = new Object[] {7, null, 123L, 2.5}; + Row nullableBuilderRow = Row.withSchema(nullableSchema).addValues(nullableVals).build(); + Row nullableArrayRow = Row.attachValues(nullableSchema, nullableVals); + Row nullableNonRaRow = Row.attachValues(nullableSchema, nonRandomAccessList(nullableVals)); + byte[] nullableBytes = encode(nullableCoder, nullableBuilderRow); + assertArrayEquals(nullableBytes, encode(nullableCoder, nullableArrayRow)); + assertArrayEquals(nullableBytes, encode(nullableCoder, nullableNonRaRow)); + assertEquals(nullableBuilderRow, nullableCoder.decode(new ByteArrayInputStream(nullableBytes))); + assertEquals(nullableBytes.length, observeSize(nullableCoder, nullableBuilderRow)); + assertEquals(nullableBytes.length, observeSize(nullableCoder, nullableArrayRow)); + + // 65..1024 fields uses a chunked generated RowFieldCodec (single-method cutoff stays at 64). + Schema.Builder wideBuilder = Schema.builder(); + Object[] wideVals = new Object[70]; + for (int i = 0; i < 70; i++) { + wideBuilder.addNullableStringField("f" + i); + wideVals[i] = (i % 7 == 0) ? null : ("v" + i); + } + Schema wideSchema = wideBuilder.build(); + RowCoder wideCoder = RowCoder.of(wideSchema); + assertTrue(RowCoderGenerator.hasGeneratedFieldCodec(RowCoderGenerator.generate(wideSchema))); + Row wideBuilderRow = Row.withSchema(wideSchema).addValues(wideVals).build(); + Row wideArrayRow = Row.attachValues(wideSchema, wideVals); + byte[] wideBytes = encode(wideCoder, wideBuilderRow); + assertArrayEquals(wideBytes, encode(wideCoder, wideArrayRow)); + assertEquals(wideBuilderRow, wideCoder.decode(new ByteArrayInputStream(wideBytes))); + } + + private static class HiddenBase { + public String baseName; + } + + @DefaultSchema(JavaFieldSchema.class) + public static class PublicSubOfHiddenBase extends HiddenBase { + public int count; + + public PublicSubOfHiddenBase() {} + + public PublicSubOfHiddenBase(String baseName, int count) { + this.baseName = baseName; + this.count = count; + } + + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof PublicSubOfHiddenBase)) { + return false; + } + PublicSubOfHiddenBase that = (PublicSubOfHiddenBase) o; + return count == that.count && Objects.equals(baseName, that.baseName); + } + + @Override + public int hashCode() { + return Objects.hash(baseName, count); + } + } + + private enum HiddenEnum { + ALPHA, + BETA + } + + @DefaultSchema(JavaFieldSchema.class) + public static class PojoWithPrivateEnum { + public HiddenEnum kind; + public int value; + + public PojoWithPrivateEnum() {} + + public PojoWithPrivateEnum(HiddenEnum kind, int value) { + this.kind = kind; + this.value = value; + } + + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof PojoWithPrivateEnum)) { + return false; + } + PojoWithPrivateEnum that = (PojoWithPrivateEnum) o; + return kind == that.kind && value == that.value; + } + + @Override + public int hashCode() { + return Objects.hash(kind, value); + } + } + + @DefaultSchema(JavaBeanSchema.class) + public static class ReentrantBean { + private static final Schema INNER_SCHEMA = + Schema.builder().addStringField("k").addInt64Field("v").build(); + private static final RowCoder INNER_CODER = RowCoder.of(INNER_SCHEMA); + + private String prefix; + private String innerTag; + private long suffix; + + public ReentrantBean() {} + + public ReentrantBean(String prefix, String innerTag, long suffix) { + this.prefix = prefix; + this.innerTag = innerTag; + this.suffix = suffix; + } + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + public String getInnerTag() { + // Trigger nested RowCoder.encode on the same thread mid-encoding to verify re-entrant + // ScratchPool safety. + try { + Row inner = Row.withSchema(INNER_SCHEMA).addValues("reentrant-" + innerTag, 999L).build(); + ByteArrayOutputStream innerOut = new ByteArrayOutputStream(); + INNER_CODER.encode(inner, innerOut); + Row decoded = INNER_CODER.decode(new ByteArrayInputStream(innerOut.toByteArray())); + if (!inner.equals(decoded)) { + throw new IllegalStateException("Reentrant inner round-trip mismatch"); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return innerTag; + } + + public void setInnerTag(String innerTag) { + this.innerTag = innerTag; + } + + public long getSuffix() { + return suffix; + } + + public void setSuffix(long suffix) { + this.suffix = suffix; + } + + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof ReentrantBean)) { + return false; + } + ReentrantBean that = (ReentrantBean) o; + return suffix == that.suffix + && Objects.equals(prefix, that.prefix) + && Objects.equals(innerTag, that.innerTag); + } + + @Override + public int hashCode() { + return Objects.hash(prefix, innerTag, suffix); + } + } + + private static final class CountingObservableCollection + extends ElementByteSizeObservableIterable> + implements java.util.Collection { + private final List elements; + final AtomicInteger createIteratorCalls = new AtomicInteger(); + + CountingObservableCollection(List elements) { + this.elements = elements; + } + + @Override + protected ElementByteSizeObservableIterator createIterator() { + createIteratorCalls.incrementAndGet(); + Iterator it = elements.iterator(); + return new ElementByteSizeObservableIterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public T next() { + T v = it.next(); + notifyValueReturned(16L); + return v; + } + }; + } + + @Override + public int size() { + return elements.size(); + } + + @Override + public boolean isEmpty() { + return elements.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return elements.contains(o); + } + + @Override + public Object[] toArray() { + return elements.toArray(); + } + + @Override + public ElemT[] toArray(ElemT[] a) { + return elements.toArray(a); + } + + @Override + public boolean add(T e) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean remove(Object o) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean containsAll(java.util.Collection c) { + return elements.containsAll(c); + } + + @Override + public boolean addAll(java.util.Collection c) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean removeAll(java.util.Collection c) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean retainAll(java.util.Collection c) { + throw new UnsupportedOperationException(); + } + + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + } + + @DefaultSchema(JavaFieldSchema.class) + public static class ObservableIterablePojo { + public java.util.Collection tags; + public java.util.Collection items; + + public ObservableIterablePojo() {} + } + + @Test + public void testReentrantEncodeDoesNotCorruptScratchBuffer() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(ReentrantBean.class); + assertTrue(coder.hasDirectCoder()); + ReentrantBean bean = new ReentrantBean("outer-prefix-abcdef", "mid-payload", 0x123456789L); + byte[] directBytes = encode(coder, bean); + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + byte[] rowBytes = encode(rowCoder, coder.getToRowFunction().apply(bean)); + assertArrayEquals(rowBytes, directBytes); + assertEquals(bean, coder.decode(new ByteArrayInputStream(directBytes))); + } + + @Test + public void testNonPublicSuperclassAndPrivateEnumFallbackGracefully() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder subCoder = + registry.getSchemaCoder(PublicSubOfHiddenBase.class); + PublicSubOfHiddenBase sub = new PublicSubOfHiddenBase("inherited", 42); + byte[] subBytes = encode(subCoder, sub); + assertEquals(sub, subCoder.decode(new ByteArrayInputStream(subBytes))); + assertArrayEquals( + encode(RowCoder.of(subCoder.getSchema()), subCoder.getToRowFunction().apply(sub)), + subBytes); + + SchemaCoder enumCoder = registry.getSchemaCoder(PojoWithPrivateEnum.class); + PojoWithPrivateEnum pe = new PojoWithPrivateEnum(HiddenEnum.BETA, 7); + byte[] enumBytes = encode(enumCoder, pe); + assertEquals(pe, enumCoder.decode(new ByteArrayInputStream(enumBytes))); + assertArrayEquals( + encode(RowCoder.of(enumCoder.getSchema()), enumCoder.getToRowFunction().apply(pe)), + enumBytes); + } + + @Test + public void testDirectSchemaCoderLazyObservableIterable() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = + registry.getSchemaCoder(ObservableIterablePojo.class); + assertTrue("Expected DirectSchemaCoder for ObservableIterablePojo", coder.hasDirectCoder()); + ObservableIterablePojo pojo = new ObservableIterablePojo(); + CountingObservableCollection tags = + new CountingObservableCollection<>(Arrays.asList("a", "b", "c")); + CountingObservableCollection items = + new CountingObservableCollection<>( + Arrays.asList(new NestedItem("x", 1, 1.0), new NestedItem("y", 2, 2.0))); + pojo.tags = tags; + pojo.items = items; + + assertTrue(coder.isRegisterByteSizeObserverCheap(pojo)); + ElementByteSizeObserver obs = + new ElementByteSizeObserver() { + @Override + protected void reportElementSize(long elementByteSize) {} + }; + coder.registerByteSizeObserver(pojo, obs); + assertTrue("Expected lazy byte-size observation", obs.getIsLazy()); + assertEquals("Should not iterate tags eagerly", 0, tags.createIteratorCalls.get()); + assertEquals("Should not iterate items eagerly", 0, items.createIteratorCalls.get()); + } + + @Test + public void testGeneratedRowCoderAndSetterCreatorSerialization() throws Exception { + Schema schema = + Schema.builder().addInt32Field("a").addNullableStringField("b").addInt64Field("c").build(); + Coder generated = RowCoderGenerator.generate(schema); + assertTrue(RowCoderGenerator.hasGeneratedFieldCodec(generated)); + Coder cloned = SerializableUtils.clone(generated); + assertTrue(RowCoderGenerator.hasGeneratedFieldCodec(cloned)); + Row row = Row.withSchema(schema).addValues(12, "hi", 34L).build(); + byte[] bytes = encode(cloned, row); + assertArrayEquals(encode(generated, row), bytes); + assertEquals(row, cloned.decode(new ByteArrayInputStream(bytes))); + + Schema beanSchema = SchemaRegistry.createDefault().getSchema(FluentCountingBean.class); + SetterBasedCreatorFactory creatorFactory = + new SetterBasedCreatorFactory( + (td, s) -> + org.apache.beam.sdk.schemas.utils.JavaBeanUtils.getSetters( + td, + s, + new JavaBeanSchema.SetterTypeSupplier(), + org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.DefaultTypeConversionsFactory + .INSTANCE)); + SchemaUserTypeCreator creator = + creatorFactory.create(TypeDescriptor.of(FluentCountingBean.class), beanSchema); + SchemaUserTypeCreator clonedCreator = SerializableUtils.clone(creator); + Object[] params = new Object[beanSchema.getFieldCount()]; + params[beanSchema.indexOf("id")] = 5; + params[beanSchema.indexOf("name")] = "cloned"; + params[beanSchema.indexOf("count")] = 99L; + params[beanSchema.indexOf("tags")] = Collections.singletonList("t"); + params[beanSchema.indexOf("metrics")] = Collections.singletonMap("k", 1L); + Object created = clonedCreator.create(params); + FluentCountingBean bean = (FluentCountingBean) created; + assertEquals(5, bean.getId()); + assertEquals("cloned", bean.getName()); + } + + @Test + public void testRowCoderNestedSchemaWithNullUuid() throws Exception { + Schema inner = Schema.builder().addStringField("s").addInt32Field("n").build(); + inner.setUUID(null); + Schema outer = + Schema.builder() + .addRowField("sub", inner) + .addArrayField("list", FieldType.row(inner)) + .build(); + RowCoder coder = RowCoder.of(outer); + Row subRow = Row.withSchema(inner).addValues("ok", 1).build(); + Row outerRow = + Row.withSchema(outer).addValues(subRow, Collections.singletonList(subRow)).build(); + byte[] bytes = encode(coder, outerRow); + assertEquals(outerRow, coder.decode(new ByteArrayInputStream(bytes))); + } + + @Test + public void testNonDirectSchemaCoderNullByteSizeCheap() { + Schema schema = Schema.builder().addStringField("s").build(); + SchemaCoder customCoder = + SchemaCoder.of( + schema, + TypeDescriptor.of(String.class), + s -> Row.withSchema(schema).addValues(s).build(), + r -> r.getString(0)); + assertFalse(customCoder.hasDirectCoder()); + assertFalse(customCoder.isRegisterByteSizeObserverCheap(null)); + } + + @Test + public void testOneOfTypeCoercionAndValidation() { + OneOfType oneOf = + OneOfType.create( + Schema.Field.of("bytes", FieldType.BYTES), + Schema.Field.of("dt", FieldType.DATETIME), + Schema.Field.of("num", FieldType.INT64)); + Row bytesRow = + oneOf.toBaseType(oneOf.createValue("bytes", ByteBuffer.wrap(new byte[] {1, 2, 3}))); + assertArrayEquals(new byte[] {1, 2, 3}, bytesRow.getBytes("bytes")); + + DateTime nonUtc = new DateTime(1_700_000_000_000L, DateTimeZone.forOffsetHours(-5)); + Row dtRow = oneOf.toBaseType(oneOf.createValue("dt", nonUtc)); + assertEquals(nonUtc.toInstant(), dtRow.getDateTime("dt").toInstant()); + + assertThrows( + RuntimeException.class, () -> oneOf.toBaseType(oneOf.createValue("num", "not-a-long"))); + } + + @Test + public void testReadNullMaskBoundsValidation() { + byte[] buf = new byte[16]; + assertThrows( + CoderException.class, + () -> RowWireCodec.readNullMask(new ByteArrayInputStream(new byte[16]), -1, buf)); + assertThrows( + CoderException.class, + () -> RowWireCodec.readNullMask(new ByteArrayInputStream(new byte[16]), 9, buf)); + } + + @Test + public void testConcurrentThreadSafetyOfScratchBuffer() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(RichPojo.class); + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + + int threads = 8; + int iterations = 1000; + ExecutorService pool = Executors.newFixedThreadPool(threads); + try { + List> futures = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + final int tid = t; + futures.add( + pool.submit( + (Callable) + () -> { + for (int i = 0; i < iterations; i++) { + RichPojo p = + sampleRichPojo( + (i % 3 == 0 ? "ascii-" : "cafรฉ-") + tid + "-" + i, + BigDecimal.valueOf((long) tid * 1000 - i, i % 5), + tid * 100 - i, + ((long) i << 20) ^ tid); + byte[] direct = encode(coder, p); + byte[] expected = encode(rowCoder, coder.getToRowFunction().apply(p)); + assertArrayEquals(expected, direct); + RichPojo decoded = coder.decode(new ByteArrayInputStream(direct)); + assertEquals(p, decoded); + } + return null; + })); + } + for (Future f : futures) { + f.get(); + } + } finally { + pool.shutdownNow(); + } + } + + /** + * 140-field POJO exercising both chunked DirectSchemaCoder (>64) and chunked POJOUtils (>128). + */ + @DefaultSchema(JavaFieldSchema.class) + public static class Wide140Pojo { + public int i00, i01, i02, i03, i04, i05, i06, i07, i08, i09; + public int i10, i11, i12, i13, i14, i15, i16, i17, i18, i19; + public int i20, i21, i22, i23, i24, i25, i26, i27, i28, i29; + public int i30, i31, i32, i33, i34; + public long l00, l01, l02, l03, l04, l05, l06, l07, l08, l09; + public long l10, l11, l12, l13, l14, l15, l16, l17, l18, l19; + public long l20, l21, l22, l23, l24, l25, l26, l27, l28, l29; + public long l30, l31, l32, l33, l34; + public double d00, d01, d02, d03, d04, d05, d06, d07, d08, d09; + public double d10, d11, d12, d13, d14, d15, d16, d17, d18, d19; + public double d20, d21, d22, d23, d24, d25, d26, d27, d28, d29; + public double d30, d31, d32, d33, d34; + public @Nullable String s00, s01, s02, s03, s04, s05, s06, s07, s08, s09; + public @Nullable String s10, s11, s12, s13, s14, s15, s16, s17, s18, s19; + public @Nullable String s20, s21, s22, s23, s24, s25, s26, s27, s28, s29; + public @Nullable String s30, s31, s32, s33, s34; + + public Wide140Pojo() { + // Non-null default to verify chunked decode explicitly overwrites defaulted fields with null. + this.s01 = "default-non-null"; + this.s34 = "default-tail"; + } + + static Wide140Pojo sample(boolean sparseNulls) { + Wide140Pojo p = new Wide140Pojo(); + p.i00 = 1; + p.i17 = 17; + p.i34 = 34; + p.l00 = 100L; + p.l17 = 1700L; + p.l34 = 3400L; + p.d00 = 0.5; + p.d17 = 17.5; + p.d34 = 34.5; + p.s00 = "first"; + p.s01 = sparseNulls ? null : "second"; + p.s17 = "mid-cafรฉ"; + p.s20 = sparseNulls ? null : "twenty"; + p.s33 = "thirty-three"; + p.s34 = sparseNulls ? null : "last"; + return p; + } + } + + private static Schema buildWideSchema(int fieldCount, boolean nullable, boolean staticEncoding) { + Schema.Builder b = Schema.builder(); + for (int i = 0; i < fieldCount; i++) { + FieldType ft; + switch (i % 8) { + case 0: + ft = FieldType.INT32; + break; + case 1: + ft = FieldType.INT64; + break; + case 2: + ft = FieldType.DOUBLE; + break; + case 3: + ft = FieldType.BOOLEAN; + break; + case 4: + ft = FieldType.STRING; + break; + case 5: + ft = FieldType.DATETIME; + break; + case 6: + ft = FieldType.BYTES; + break; + default: + ft = FieldType.FLOAT; + break; + } + if (nullable) { + ft = ft.withNullable(true); + } + b.addField("f_" + i, ft); + } + if (staticEncoding) { + b.setOptions( + Schema.Options.builder() + .setOption("beam:option:row:static_encoding", FieldType.BOOLEAN, true) + .build()); + } + return b.build(); + } + + private static Row buildWideRow(Schema schema, boolean sparseNulls, boolean arrayBacked) { + int n = schema.getFieldCount(); + Object[] arr = new Object[n]; + for (int i = 0; i < n; i++) { + if (sparseNulls && (i % 3 == 0 || i == n - 1)) { + arr[i] = null; + continue; + } + switch (i % 8) { + case 0: + arr[i] = 1000 + i; + break; + case 1: + arr[i] = 1_000_000_000L + i; + break; + case 2: + arr[i] = 3.25 + i; + break; + case 3: + arr[i] = (i & 1) == 0; + break; + case 4: + arr[i] = "val-" + i; + break; + case 5: + arr[i] = Instant.ofEpochMilli(1_700_000_000_000L + i); + break; + case 6: + arr[i] = ("b-" + i).getBytes(StandardCharsets.UTF_8); + break; + default: + arr[i] = 1.5f + i; + break; + } + } + return arrayBacked + ? Row.attachValues(schema, arr) + : Row.withSchema(schema).attachValues(new ArrayList<>(Arrays.asList(arr))); + } + + @Test + public void testChunkedRowCoder300FieldsRoundTripAndEvolution() throws Exception { + for (boolean nullable : new boolean[] {false, true}) { + Schema schema = buildWideSchema(300, nullable, false); + Coder coder = RowCoderGenerator.generate(schema); + assertTrue( + "Expected chunked generated field codec for 300-field schema", + RowCoderGenerator.hasGeneratedFieldCodec(coder)); + + // Verify Java serialization preserves chunked codec. + Coder cloned = SerializableUtils.clone(coder); + assertTrue(RowCoderGenerator.hasGeneratedFieldCodec(cloned)); + + for (boolean arrayBacked : new boolean[] {true, false}) { + Row nonNullRow = buildWideRow(schema, false, arrayBacked); + byte[] bytes = encode(cloned, nonNullRow); + assertEquals(nonNullRow, cloned.decode(new ByteArrayInputStream(bytes))); + assertEquals(bytes.length, observeSize(cloned, nonNullRow)); + + if (nullable) { + Row sparseRow = buildWideRow(schema, true, arrayBacked); + byte[] sparseBytes = encode(cloned, sparseRow); + assertEquals(sparseRow, cloned.decode(new ByteArrayInputStream(sparseBytes))); + assertEquals(sparseBytes.length, observeSize(cloned, sparseRow)); + + // All-null row exercises full 38-byte bitmap. + Row allNullRow = Row.attachValues(schema, new Object[300]); + byte[] allNullBytes = encode(cloned, allNullRow); + assertEquals(allNullRow, cloned.decode(new ByteArrayInputStream(allNullBytes))); + assertEquals(allNullBytes.length, observeSize(cloned, allNullRow)); + } + } + } + + // Static encoding 300-field row. + Schema staticSchema = buildWideSchema(300, false, true); + Coder staticCoder = RowCoderGenerator.generate(staticSchema); + assertTrue(RowCoderGenerator.hasGeneratedFieldCodec(staticCoder)); + Row staticRow = buildWideRow(staticSchema, false, true); + byte[] staticBytes = encode(staticCoder, staticRow); + assertEquals(staticRow, staticCoder.decode(new ByteArrayInputStream(staticBytes))); + assertEquals(staticBytes.length, observeSize(staticCoder, staticRow)); + + // Schema evolution: stream written with 200 fields decoded by 300-field schema (nullable). + Schema s200 = buildWideSchema(200, true, false); + Schema s300 = buildWideSchema(300, true, false); + Row row200 = buildWideRow(s200, true, true); + byte[] bytes200 = encode(RowCoder.of(s200), row200); + Row decoded300 = RowCoder.of(s300).decode(new ByteArrayInputStream(bytes200)); + for (int i = 0; i < 200; i++) { + if (s200.getField(i).getType().getTypeName() == Schema.TypeName.BYTES) { + assertArrayEquals(row200.getBytes(i), decoded300.getBytes(i)); + } else { + Object expectedVal = row200.getValue(i); + Object actualVal = decoded300.getValue(i); + assertEquals(expectedVal, actualVal); + } + } + for (int i = 200; i < 300; i++) { + assertNull(decoded300.getValue(i)); + } + } + + @Test + public void testVeryWideRowCoder1100FieldsLoopFallback() throws Exception { + Schema schema = buildWideSchema(1100, true, false); + Coder coder = RowCoderGenerator.generate(schema); + assertFalse( + "Schemas above 1024 fields should use the buffered loop fallback", + RowCoderGenerator.hasGeneratedFieldCodec(coder)); + Row row = buildWideRow(schema, true, true); + byte[] bytes = encode(coder, row); + assertEquals(row, coder.decode(new ByteArrayInputStream(bytes))); + assertEquals(bytes.length, observeSize(coder, row)); + } + + @Test + public void testChunkedDirectSchemaCoderAndChunkedPojoCreator140Fields() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(Wide140Pojo.class); + assertEquals(140, coder.getSchema().getFieldCount()); + assertTrue("Expected chunked DirectSchemaCoder for Wide140Pojo", coder.hasDirectCoder()); + + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + for (boolean sparseNulls : new boolean[] {false, true}) { + Wide140Pojo sample = Wide140Pojo.sample(sparseNulls); + byte[] directBytes = encode(coder, sample); + Row asRow = coder.getToRowFunction().apply(sample); + byte[] rowBytes = encode(rowCoder, asRow); + assertArrayEquals(rowBytes, directBytes); + + assertTrue(coder.isRegisterByteSizeObserverCheap(sample)); + assertEquals(directBytes.length, observeSize(coder, sample)); + + Wide140Pojo decodedDirect = coder.decode(new ByteArrayInputStream(directBytes)); + assertEquals(asRow, coder.getToRowFunction().apply(decodedDirect)); + + // Also exercise chunked POJOUtils.SetFieldCreateInstruction (>128 fields) via + // fromRowFunction. + Row decodedRow = rowCoder.decode(new ByteArrayInputStream(rowBytes)); + Wide140Pojo fromRow = coder.getFromRowFunction().apply(decodedRow); + assertEquals(asRow, coder.getToRowFunction().apply(fromRow)); + } + } + + @Test + public void testRowWithGettersCompactContainerCacheOnWideSchema() { + Schema.Builder b = Schema.builder(); + for (int i = 0; i < 300; i++) { + if (i == 5) { + b.addNullableArrayField("list_5", FieldType.STRING); + } else if (i == 250) { + b.addNullableMapField("map_250", FieldType.STRING, FieldType.INT64); + } else { + b.addInt32Field("f_" + i); + } + } + Schema schema = b.build(); + assertEquals(2, schema.getCacheableContainerCount()); + assertEquals(0, schema.getContainerCacheSlot(5)); + assertEquals(1, schema.getContainerCacheSlot(250)); + assertEquals(-1, schema.getContainerCacheSlot(0)); + assertEquals(-1, schema.getContainerCacheSlot(100)); + assertEquals(-1, schema.getContainerCacheSlot(299)); + + AtomicInteger listCalls = new AtomicInteger(); + AtomicInteger mapCalls = new AtomicInteger(); + List> getters = new ArrayList<>(300); + for (int i = 0; i < 300; i++) { + final int idx = i; + getters.add( + new FieldValueGetter() { + @Override + public Object get(Object object) { + if (idx == 5) { + listCalls.incrementAndGet(); + return Arrays.asList("a", "b"); + } + if (idx == 250) { + mapCalls.incrementAndGet(); + return null; // exercises NULL_SENTINEL caching in compact slot 1 + } + return idx; + } + + @Override + public String name() { + return schema.getField(idx).getName(); + } + }); + } + + Row row = + Row.withFieldValueGetters(schema, getters, new Object(), TypeDescriptor.of(Object.class)); + assertEquals(Integer.valueOf(42), row.getInt32(42)); + assertEquals(Arrays.asList("a", "b"), new ArrayList<>(Objects.requireNonNull(row.getArray(5)))); + assertEquals(Arrays.asList("a", "b"), new ArrayList<>(Objects.requireNonNull(row.getArray(5)))); + assertNull(row.getMap(250)); + assertNull(row.getMap(250)); + assertEquals("Container getter at index 5 should be cached", 1, listCalls.get()); + assertEquals("Null container getter at index 250 should be cached", 1, mapCalls.get()); + } + + /** + * 68-field JavaBean exercising chunked DirectSchemaCoder (>64 fields, 3 chunks) with nullable + * getters, non-null constructor defaults, fluent setters, and single-evaluation getter tracking. + */ + @DefaultSchema(JavaBeanSchema.class) + public static class Wide68Bean { + private final int[] iv = new int[34]; + private final @Nullable String[] sv = new String[34]; + final transient int[] strGetterCounts = new int[34]; + + public Wide68Bean() { + sv[1] = "default-s01"; + sv[33] = "default-s33"; + } + + private @Nullable String readStr(int idx) { + strGetterCounts[idx]++; + return sv[idx]; + } + + void resetGetterCounts() { + Arrays.fill(strGetterCounts, 0); + } + + static Wide68Bean sample(boolean sparseNulls) { + Wide68Bean b = new Wide68Bean(); + for (int i = 0; i < 34; i++) { + b.iv[i] = 100 + i; + b.sv[i] = (sparseNulls && (i == 1 || i == 17 || i == 33)) ? null : ("str-" + i); + } + return b; + } + + public int getI00() { + return iv[0]; + } + + public void setI00(int v) { + iv[0] = v; + } + + public int getI01() { + return iv[1]; + } + + public void setI01(int v) { + iv[1] = v; + } + + public int getI02() { + return iv[2]; + } + + public void setI02(int v) { + iv[2] = v; + } + + public int getI03() { + return iv[3]; + } + + public void setI03(int v) { + iv[3] = v; + } + + public int getI04() { + return iv[4]; + } + + public void setI04(int v) { + iv[4] = v; + } + + public int getI05() { + return iv[5]; + } + + public void setI05(int v) { + iv[5] = v; + } + + public int getI06() { + return iv[6]; + } + + public void setI06(int v) { + iv[6] = v; + } + + public int getI07() { + return iv[7]; + } + + public void setI07(int v) { + iv[7] = v; + } + + public int getI08() { + return iv[8]; + } + + public void setI08(int v) { + iv[8] = v; + } + + public int getI09() { + return iv[9]; + } + + public void setI09(int v) { + iv[9] = v; + } + + public int getI10() { + return iv[10]; + } + + public void setI10(int v) { + iv[10] = v; + } + + public int getI11() { + return iv[11]; + } + + public void setI11(int v) { + iv[11] = v; + } + + public int getI12() { + return iv[12]; + } + + public void setI12(int v) { + iv[12] = v; + } + + public int getI13() { + return iv[13]; + } + + public void setI13(int v) { + iv[13] = v; + } + + public int getI14() { + return iv[14]; + } + + public void setI14(int v) { + iv[14] = v; + } + + public int getI15() { + return iv[15]; + } + + public void setI15(int v) { + iv[15] = v; + } + + public int getI16() { + return iv[16]; + } + + public void setI16(int v) { + iv[16] = v; + } + + public int getI17() { + return iv[17]; + } + + public void setI17(int v) { + iv[17] = v; + } + + public int getI18() { + return iv[18]; + } + + public void setI18(int v) { + iv[18] = v; + } + + public int getI19() { + return iv[19]; + } + + public void setI19(int v) { + iv[19] = v; + } + + public int getI20() { + return iv[20]; + } + + public void setI20(int v) { + iv[20] = v; + } + + public int getI21() { + return iv[21]; + } + + public void setI21(int v) { + iv[21] = v; + } + + public int getI22() { + return iv[22]; + } + + public void setI22(int v) { + iv[22] = v; + } + + public int getI23() { + return iv[23]; + } + + public void setI23(int v) { + iv[23] = v; + } + + public int getI24() { + return iv[24]; + } + + public void setI24(int v) { + iv[24] = v; + } + + public int getI25() { + return iv[25]; + } + + public void setI25(int v) { + iv[25] = v; + } + + public int getI26() { + return iv[26]; + } + + public void setI26(int v) { + iv[26] = v; + } + + public int getI27() { + return iv[27]; + } + + public void setI27(int v) { + iv[27] = v; + } + + public int getI28() { + return iv[28]; + } + + public void setI28(int v) { + iv[28] = v; + } + + public int getI29() { + return iv[29]; + } + + public void setI29(int v) { + iv[29] = v; + } + + public int getI30() { + return iv[30]; + } + + public void setI30(int v) { + iv[30] = v; + } + + public int getI31() { + return iv[31]; + } + + public void setI31(int v) { + iv[31] = v; + } + + public int getI32() { + return iv[32]; + } + + public void setI32(int v) { + iv[32] = v; + } + + public int getI33() { + return iv[33]; + } + + public void setI33(int v) { + iv[33] = v; + } + + @SuppressWarnings("nullness") + public String getS00() { + return readStr(0); + } + + public void setS00(String v) { + sv[0] = v; + } + + void clearRequiredS00ForTest() { + sv[0] = null; + } + + public @Nullable String getS01() { + return readStr(1); + } + + public Wide68Bean setS01(@Nullable String v) { + sv[1] = v; + return this; + } + + public @Nullable String getS02() { + return readStr(2); + } + + public void setS02(@Nullable String v) { + sv[2] = v; + } + + public @Nullable String getS03() { + return readStr(3); + } + + public void setS03(@Nullable String v) { + sv[3] = v; + } + + public @Nullable String getS04() { + return readStr(4); + } + + public void setS04(@Nullable String v) { + sv[4] = v; + } + + public @Nullable String getS05() { + return readStr(5); + } + + public void setS05(@Nullable String v) { + sv[5] = v; + } + + public @Nullable String getS06() { + return readStr(6); + } + + public void setS06(@Nullable String v) { + sv[6] = v; + } + + public @Nullable String getS07() { + return readStr(7); + } + + public void setS07(@Nullable String v) { + sv[7] = v; + } + + public @Nullable String getS08() { + return readStr(8); + } + + public void setS08(@Nullable String v) { + sv[8] = v; + } + + public @Nullable String getS09() { + return readStr(9); + } + + public void setS09(@Nullable String v) { + sv[9] = v; + } + + public @Nullable String getS10() { + return readStr(10); + } + + public void setS10(@Nullable String v) { + sv[10] = v; + } + + public @Nullable String getS11() { + return readStr(11); + } + + public void setS11(@Nullable String v) { + sv[11] = v; + } + + public @Nullable String getS12() { + return readStr(12); + } + + public void setS12(@Nullable String v) { + sv[12] = v; + } + + public @Nullable String getS13() { + return readStr(13); + } + + public void setS13(@Nullable String v) { + sv[13] = v; + } + + public @Nullable String getS14() { + return readStr(14); + } + + public void setS14(@Nullable String v) { + sv[14] = v; + } + + public @Nullable String getS15() { + return readStr(15); + } + + public void setS15(@Nullable String v) { + sv[15] = v; + } + + public @Nullable String getS16() { + return readStr(16); + } + + public void setS16(@Nullable String v) { + sv[16] = v; + } + + public @Nullable String getS17() { + return readStr(17); + } + + public void setS17(@Nullable String v) { + sv[17] = v; + } + + public @Nullable String getS18() { + return readStr(18); + } + + public void setS18(@Nullable String v) { + sv[18] = v; + } + + public @Nullable String getS19() { + return readStr(19); + } + + public void setS19(@Nullable String v) { + sv[19] = v; + } + + public @Nullable String getS20() { + return readStr(20); + } + + public void setS20(@Nullable String v) { + sv[20] = v; + } + + public @Nullable String getS21() { + return readStr(21); + } + + public void setS21(@Nullable String v) { + sv[21] = v; + } + + public @Nullable String getS22() { + return readStr(22); + } + + public void setS22(@Nullable String v) { + sv[22] = v; + } + + public @Nullable String getS23() { + return readStr(23); + } + + public void setS23(@Nullable String v) { + sv[23] = v; + } + + public @Nullable String getS24() { + return readStr(24); + } + + public void setS24(@Nullable String v) { + sv[24] = v; + } + + public @Nullable String getS25() { + return readStr(25); + } + + public void setS25(@Nullable String v) { + sv[25] = v; + } + + public @Nullable String getS26() { + return readStr(26); + } + + public void setS26(@Nullable String v) { + sv[26] = v; + } + + public @Nullable String getS27() { + return readStr(27); + } + + public void setS27(@Nullable String v) { + sv[27] = v; + } + + public @Nullable String getS28() { + return readStr(28); + } + + public void setS28(@Nullable String v) { + sv[28] = v; + } + + public @Nullable String getS29() { + return readStr(29); + } + + public void setS29(@Nullable String v) { + sv[29] = v; + } + + public @Nullable String getS30() { + return readStr(30); + } + + public void setS30(@Nullable String v) { + sv[30] = v; + } + + public @Nullable String getS31() { + return readStr(31); + } + + public void setS31(@Nullable String v) { + sv[31] = v; + } + + public @Nullable String getS32() { + return readStr(32); + } + + public void setS32(@Nullable String v) { + sv[32] = v; + } + + public @Nullable String getS33() { + return readStr(33); + } + + public Wide68Bean setS33(@Nullable String v) { + sv[33] = v; + return this; + } + } + + @Test + public void testChunkedDirectSchemaCoderWideJavaBeanEvaluateOnce() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(Wide68Bean.class); + assertEquals(68, coder.getSchema().getFieldCount()); + assertTrue("Expected chunked DirectSchemaCoder for Wide68Bean", coder.hasDirectCoder()); + + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + for (boolean sparseNulls : new boolean[] {false, true}) { + Wide68Bean sample = Wide68Bean.sample(sparseNulls); + sample.resetGetterCounts(); + byte[] directBytes = encode(coder, sample); + for (int i = 0; i < 34; i++) { + assertEquals( + "Nullable getter s" + i + " must be evaluated exactly once during chunked encode", + 1, + sample.strGetterCounts[i]); + } + + Row asRow = coder.getToRowFunction().apply(sample); + byte[] rowBytes = encode(rowCoder, asRow); + assertArrayEquals(rowBytes, directBytes); + + assertTrue(coder.isRegisterByteSizeObserverCheap(sample)); + assertEquals(directBytes.length, observeSize(coder, sample)); + + Wide68Bean decoded = coder.decode(new ByteArrayInputStream(directBytes)); + assertEquals(asRow, coder.getToRowFunction().apply(decoded)); + if (sparseNulls) { + assertNull(decoded.getS01()); + assertNull(decoded.getS17()); + assertNull(decoded.getS33()); + } + } + + // Exercise chunk bit-31 null (s29 is field index 63 = chunk 1 bit 31 in alphabetical bean + // order) + // and Java serialization round-trip of chunked JavaBean SchemaCoder. + SchemaCoder cloned = SerializableUtils.clone(coder); + assertTrue(cloned.hasDirectCoder()); + Wide68Bean bit31Null = Wide68Bean.sample(false); + bit31Null.setS29(null); + bit31Null.resetGetterCounts(); + byte[] bit31Bytes = encode(cloned, bit31Null); + for (int i = 0; i < 34; i++) { + assertEquals(1, bit31Null.strGetterCounts[i]); + } + Wide68Bean decodedBit31 = cloned.decode(new ByteArrayInputStream(bit31Bytes)); + assertNull(decodedBit31.getS29()); + assertEquals( + cloned.getToRowFunction().apply(bit31Null), cloned.getToRowFunction().apply(decodedBit31)); + + // Null in non-nullable reference field s00 must throw RuntimeException in nullScanBeanC* and + // ByteSizeChunkImpl (emitThrowNullNonNullable). + Wide68Bean missingReq = Wide68Bean.sample(false); + missingReq.clearRequiredS00ForTest(); + RuntimeException encNullEx = + assertThrows(RuntimeException.class, () -> encode(coder, missingReq)); + assertTrue( + encNullEx.getMessage() != null + && encNullEx.getMessage().contains("Null value set on non-nullable field")); + RuntimeException sizeNullEx = + assertThrows(RuntimeException.class, () -> observeSize(coder, missingReq)); + assertTrue( + sizeNullEx.getMessage() != null + && sizeNullEx.getMessage().contains("Null value set on non-nullable field")); + } + + @Test + public void testRowWireCodecVarIntAndVarLongEdgeCases() throws Exception { + int[] intVals = { + 0, + 1, + 127, + 128, + 1000, + 16383, + 16384, + (1 << 21) - 1, + 1 << 21, + (1 << 28) - 1, + 1 << 28, + Integer.MAX_VALUE, + -1, + -128, + Integer.MIN_VALUE + }; + for (int v : intVals) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + VarInt.encode(v, out); + assertEquals(v, RowWireCodec.readVarInt(new ByteArrayInputStream(out.toByteArray()))); + } + // Non-canonical 6-byte encoding of 0 must still decode to 0. + assertEquals( + 0, + RowWireCodec.readVarInt( + new ByteArrayInputStream( + new byte[] {(byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, 0}))); + // 5-byte 32-bit overflow (1L << 32), 6-byte overflow (1L << 40), and negative long (-1L). + for (long over : new long[] {1L << 32, 1L << 40, -1L}) { + ByteArrayOutputStream overOut = new ByteArrayOutputStream(); + VarInt.encode(over, overOut); + assertThrows( + IOException.class, + () -> RowWireCodec.readVarInt(new ByteArrayInputStream(overOut.toByteArray()))); + } + // EOF on byte 0 vs unterminated at byte 2, 3, 4, 5, and 6. + assertThrows( + CoderException.class, () -> RowWireCodec.readVarInt(new ByteArrayInputStream(new byte[0]))); + for (int len = 1; len <= 5; len++) { + byte[] trunc = new byte[len]; + Arrays.fill(trunc, (byte) 0x80); + assertThrows( + IOException.class, () -> RowWireCodec.readVarInt(new ByteArrayInputStream(trunc))); + } + + long[] longVals = { + 0L, + 1L, + 127L, + 128L, + 16383L, + 16384L, + (1L << 21) - 1, + 1L << 21, + (1L << 28) - 1, + 1L << 28, + 1_000_000_000L, + (1L << 35) - 1, + 1L << 35, + 1_700_000_000_000L, + (1L << 49) - 1, + (1L << 63) - 1, + Long.MAX_VALUE, + -1L, + Long.MIN_VALUE + }; + for (long v : longVals) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + VarInt.encode(v, out); + assertEquals(v, RowWireCodec.readVarLong(new ByteArrayInputStream(out.toByteArray()))); + } + assertThrows( + CoderException.class, + () -> RowWireCodec.readVarLong(new ByteArrayInputStream(new byte[0]))); + for (int len = 1; len <= 9; len++) { + byte[] trunc = new byte[len]; + Arrays.fill(trunc, (byte) 0x81); + assertThrows( + IOException.class, () -> RowWireCodec.readVarLong(new ByteArrayInputStream(trunc))); + } + // 10th byte > 1 and 11-byte stream both overflow 64-bit unsigned varlong. + byte[] bad10 = new byte[] {-1, -1, -1, -1, -1, -1, -1, -1, -1, 2}; + assertThrows( + IOException.class, () -> RowWireCodec.readVarLong(new ByteArrayInputStream(bad10))); + byte[] bad11 = new byte[] {-128, -128, -128, -128, -128, -128, -128, -128, -128, -128, 0}; + assertThrows( + IOException.class, () -> RowWireCodec.readVarLong(new ByteArrayInputStream(bad11))); + } + + /** + * InputStream that delivers at most 1 byte per read(byte[], int, int) call to exercise + * readExactSlow. + */ + private static final class OneByteAtATimeInputStream extends InputStream { + private final byte[] data; + private int pos; + + OneByteAtATimeInputStream(byte[] data) { + this.data = data; + } + + @Override + public int read() { + return pos < data.length ? (data[pos++] & 0xFF) : -1; + } + + @Override + public int read(byte[] b, int off, int len) { + if (pos >= data.length) { + return -1; + } + if (len <= 0) { + return 0; + } + b[off] = data[pos++]; + return 1; + } + } + + @Test + public void testRowWireCodecZeroLenReadNullBytesShortVarHandleAndPools() throws Exception { + byte[] scratch = new byte[512]; + // Zero-length reads at EOF on ByteArrayInputStream must succeed (C1 regression guard). + assertEquals(0L, RowWireCodec.readNullMask(new ByteArrayInputStream(new byte[0]), 0, scratch)); + assertSame( + scratch, RowWireCodec.readNullBytes(new ByteArrayInputStream(new byte[0]), 0, scratch)); + // Negative nullByteLen must throw CoderException in readNullBytes and packWideNullHeader. + assertThrows( + CoderException.class, + () -> RowWireCodec.readNullBytes(new ByteArrayInputStream(new byte[4]), -1, scratch)); + assertThrows( + CoderException.class, + () -> + RowWireCodec.packWideNullHeader( + 100, new byte[4], -1, scratch, new ByteArrayOutputStream())); + + // packWideNullHeader boundary tests: 0, 502 (fits 512), 503 & 513 (direct stream), small buf. + for (int nullLen : new int[] {0, 502, 503, 513}) { + byte[] bitmap = new byte[nullLen]; + for (int i = 0; i < nullLen; i++) { + bitmap[i] = (byte) ((i * 31 + 7) & 0xFF); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int pos = RowWireCodec.packWideNullHeader(5000, bitmap, nullLen, scratch, out); + RowWireCodec.flush(scratch, pos, out); + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + assertEquals(5000, RowWireCodec.readVarInt(in)); + int decodedLen = RowWireCodec.readVarInt(in); + assertEquals(nullLen, decodedLen); + byte[] read = RowWireCodec.readNullBytes(in, decodedLen, scratch); + if (nullLen <= scratch.length) { + assertSame(scratch, read); + } + for (int i = 0; i < nullLen; i++) { + assertEquals(bitmap[i], read[i]); + } + } + // Custom undersized buffer (< 10 bytes) must not throw ArrayIndexOutOfBoundsException (C3). + ByteArrayOutputStream smallBufOut = new ByteArrayOutputStream(); + byte[] smallBuf = new byte[4]; + byte[] b8 = new byte[] {1, 2, 3, 4, 5, 6, 7, 8}; + int sp = RowWireCodec.packWideNullHeader(200, b8, 8, smallBuf, smallBufOut); + RowWireCodec.flush(smallBuf, sp, smallBufOut); + ByteArrayInputStream sbi = new ByteArrayInputStream(smallBufOut.toByteArray()); + assertEquals(200, RowWireCodec.readVarInt(sbi)); + assertEquals(8, RowWireCodec.readVarInt(sbi)); + byte[] readSmall = RowWireCodec.readNullBytes(sbi, 8, smallBuf); + assertArrayEquals(b8, readSmall); + + // extractChunkNullMask32 partial chunks (1, 2, 3 bytes), full 4-byte chunk with bit 31 set, + // OOB. + assertEquals(0, RowWireCodec.extractChunkNullMask32(new byte[0], 0, 0)); + byte[] maskBytes = new byte[] {0x12, 0x34, 0x56, (byte) 0x80, 0x01, 0x02, 0x03}; + assertEquals(0x80563412, RowWireCodec.extractChunkNullMask32(maskBytes, 7, 0)); + assertEquals(0x00030201, RowWireCodec.extractChunkNullMask32(maskBytes, 7, 1)); + assertEquals(0x00000201, RowWireCodec.extractChunkNullMask32(maskBytes, 6, 1)); + assertEquals(0x00000001, RowWireCodec.extractChunkNullMask32(maskBytes, 5, 1)); + assertEquals(0, RowWireCodec.extractChunkNullMask32(maskBytes, 7, 2)); + + // SHORT_BE VarHandle packInt16 / readInt16 boundaries vs BigEndianShortCoder. + BigEndianShortCoder shortCoder = BigEndianShortCoder.of(); + for (short s : + new short[] {Short.MIN_VALUE, -1000, -128, -1, 0, 1, 127, 1000, Short.MAX_VALUE}) { + ByteArrayOutputStream actual = new ByteArrayOutputStream(); + int p = RowWireCodec.packInt16(s, scratch, 0, actual); + RowWireCodec.flush(scratch, p, actual); + byte[] expected = encode(shortCoder, s); + assertArrayEquals(expected, actual.toByteArray()); + assertEquals(s, RowWireCodec.readInt16(new ByteArrayInputStream(expected), scratch)); + assertEquals(s, RowWireCodec.readInt16(new OneByteAtATimeInputStream(expected), scratch)); + } + + // Exercise readExactSlow partial reads on readDouble, readFloat, readString, readNullBytes. + ByteArrayOutputStream slowStream = new ByteArrayOutputStream(); + int p = RowWireCodec.packDouble(3.141592653589793, scratch, 0, slowStream); + p = RowWireCodec.packFloat(-2.5f, scratch, p, slowStream); + p = RowWireCodec.packString("partial-read-utf8-cafรฉ", scratch, p, slowStream); + RowWireCodec.flush(scratch, p, slowStream); + OneByteAtATimeInputStream slowIn = new OneByteAtATimeInputStream(slowStream.toByteArray()); + assertEquals(3.141592653589793, RowWireCodec.readDouble(slowIn, scratch), 0.0); + assertEquals(-2.5f, RowWireCodec.readFloat(slowIn, scratch), 0.0f); + assertEquals("partial-read-utf8-cafรฉ", RowWireCodec.readString(slowIn, scratch)); + + // Error branches on readByte, readBoolean, readString, readBytes. + assertThrows( + CoderException.class, () -> RowWireCodec.readByte(new ByteArrayInputStream(new byte[0]))); + assertThrows( + CoderException.class, + () -> RowWireCodec.readBoolean(new ByteArrayInputStream(new byte[0]))); + assertThrows( + IOException.class, + () -> RowWireCodec.readBoolean(new ByteArrayInputStream(new byte[] {2}))); + ByteArrayOutputStream negLen = new ByteArrayOutputStream(); + VarInt.encode(-1, negLen); + assertThrows( + CoderException.class, + () -> RowWireCodec.readString(new ByteArrayInputStream(negLen.toByteArray()), scratch)); + assertThrows( + CoderException.class, + () -> RowWireCodec.readBytes(new ByteArrayInputStream(negLen.toByteArray()))); + assertArrayEquals( + new byte[0], RowWireCodec.readBytes(new ByteArrayInputStream(new byte[] {0}))); + // >512-byte string hits readStringSlow. + StringBuilder longSb = new StringBuilder(700); + for (int i = 0; i < 700; i++) { + longSb.append((char) ('a' + (i % 26))); + } + String longStr = longSb.toString(); + ByteArrayOutputStream longStrOut = new ByteArrayOutputStream(); + p = RowWireCodec.packString(longStr, scratch, 0, longStrOut); + RowWireCodec.flush(scratch, p, longStrOut); + assertEquals( + longStr, + RowWireCodec.readString(new ByteArrayInputStream(longStrOut.toByteArray()), scratch)); + + // RefScratchPool re-entrancy & reference clearing for GC safety. + RowWireCodec.RefScratchPool refPool = RowWireCodec.refScratchPool(); + Object[] r1 = refPool.acquire(10); + Object[] r2 = refPool.acquire(10); + assertTrue("Re-entrant acquire must return distinct arrays", r1 != r2); + r1[0] = "secret"; + r1[9] = "tail"; + refPool.release(r1, 10); + refPool.release(r2, 10); + assertNull("Released RefScratchPool slots must be nulled for GC", r1[0]); + assertNull("Released RefScratchPool slots must be nulled for GC", r1[9]); + } + + @Test + public void testWideRowCoderCutoffsOverridesRowBodyRichTypesEvolutionAndHuge4200() + throws Exception { + // Exact cutoff boundaries: 64 (unrolled), 65 (chunked), 1024 (chunked max), 1025 (loop). + for (int width : new int[] {64, 65, 1024, 1025}) { + Schema s = buildWideSchema(width, true, false); + Coder c = RowCoderGenerator.generate(s); + assertEquals( + "hasGeneratedFieldCodec mismatch at width=" + width, + width <= 1024, + RowCoderGenerator.hasGeneratedFieldCodec(c)); + Row r = buildWideRow(s, true, true); + byte[] bytes = encode(c, r); + assertEquals(r, c.decode(new ByteArrayInputStream(bytes))); + assertEquals(bytes.length, observeSize(c, r)); + } + + // Exercise encRowC* (non-RowWithStorage RowWithGetters on wide non-nullable + static schemas). + for (boolean staticEnc : new boolean[] {false, true}) { + Schema s70 = buildWideSchema(70, false, staticEnc); + RowCoder c70 = RowCoder.of(s70); + Row storageRow = buildWideRow(s70, false, true); + List> getters = new ArrayList<>(70); + for (int i = 0; i < 70; i++) { + final int idx = i; + getters.add( + new FieldValueGetter() { + @Override + public Object get(Row object) { + return object.getValue(idx); + } + + @Override + public String name() { + return s70.getField(idx).getName(); + } + }); + } + Row gettersRow = + Row.withFieldValueGetters(s70, getters, storageRow, TypeDescriptor.of(Row.class)); + byte[] storageBytes = encode(c70, storageRow); + byte[] gettersBytes = encode(c70, gettersRow); + assertArrayEquals(storageBytes, gettersBytes); + assertEquals(storageRow, c70.decode(new ByteArrayInputStream(gettersBytes))); + assertTrue(c70.isRegisterByteSizeObserverCheap(gettersRow)); + assertEquals(gettersBytes.length, observeSize(c70, gettersRow)); + + // Non-RandomAccess list on wide non-nullable / static schema. + Object[] rawNn = new Object[70]; + for (int i = 0; i < 70; i++) { + rawNn[i] = storageRow.getValue(i); + } + Row nonRaNn = Row.attachValues(s70, nonRandomAccessList(rawNn)); + assertArrayEquals(storageBytes, encode(c70, nonRaNn)); + } + + // Non-RandomAccess list and staticEncoding + nullable on wide schema. + Schema s70Null = buildWideSchema(70, true, false); + RowCoder c70Null = RowCoder.of(s70Null); + Row arr70Null = buildWideRow(s70Null, true, true); + Object[] raw70 = new Object[70]; + for (int i = 0; i < 70; i++) { + raw70[i] = arr70Null.getValue(i); + } + Row nonRa70Null = Row.attachValues(s70Null, nonRandomAccessList(raw70)); + byte[] arr70Bytes = encode(c70Null, arr70Null); + assertArrayEquals(arr70Bytes, encode(c70Null, nonRa70Null)); + assertEquals(arr70Null, c70Null.decode(new ByteArrayInputStream(arr70Bytes))); + + Schema s70StaticNull = buildWideSchema(70, true, true); + RowCoder c70StaticNull = RowCoder.of(s70StaticNull); + Row r70StaticNull = buildWideRow(s70StaticNull, false, true); + byte[] staticNullBytes = encode(c70StaticNull, r70StaticNull); + assertEquals(r70StaticNull, c70StaticNull.decode(new ByteArrayInputStream(staticNullBytes))); + + // Wide all-int schema exercises !needsDecodeScratch (0 ScratchPool checkouts) and O(1) isCheap. + Schema.Builder intOnlyB = Schema.builder(); + Object[] intOnlyVals = new Object[70]; + for (int i = 0; i < 70; i++) { + intOnlyB.addNullableInt32Field("i_" + i); + intOnlyVals[i] = (i == 1 || i == 69) ? null : (i * 100); + } + Schema intOnlyS = intOnlyB.build(); + RowCoder intOnlyC = RowCoder.of(intOnlyS); + Row intOnlyRow = Row.attachValues(intOnlyS, intOnlyVals); + byte[] intOnlyBytes = encode(intOnlyC, intOnlyRow); + assertEquals(intOnlyRow, intOnlyC.decode(new ByteArrayInputStream(intOnlyBytes))); + assertTrue(intOnlyC.isRegisterByteSizeObserverCheap(intOnlyRow)); + assertEquals(intOnlyBytes.length, observeSize(intOnlyC, intOnlyRow)); + + // Rich 70-field wide RowCoder touching coders, elemCoders, mid-chunk emitFlush, and all kinds. + Schema nestedS = Schema.builder().addStringField("k").addInt32Field("v").build(); + Schema.Builder richB = Schema.builder(); + List richVals = new ArrayList<>(70); + richB.addByteField("f_byte"); + richVals.add((byte) -7); + richB.addInt16Field("f_short"); + richVals.add((short) -1234); + richB.addDecimalField("f_dec"); + richVals.add(new BigDecimal("12345.67")); + richB.addLogicalTypeField("f_date", new Date()); + richVals.add(LocalDate.of(2026, 5, 19)); + richB.addLogicalTypeField("f_time", new Time()); + richVals.add(LocalTime.of(12, 34, 56, 789)); + richB.addLogicalTypeField("f_ldt", new org.apache.beam.sdk.schemas.logicaltypes.DateTime()); + richVals.add(LocalDateTime.of(2026, 5, 19, 12, 34, 56)); + richB.addLogicalTypeField("f_uuid", new UuidLogicalType()); + richVals.add(new UUID(123L, 456L)); + richB.addLogicalTypeField("f_micros", new MicrosInstant()); + richVals.add(java.time.Instant.ofEpochSecond(1_700_000_000L, 123_000L)); + richB.addLogicalTypeField("f_nanos", new NanosInstant()); + richVals.add(java.time.Instant.ofEpochSecond(1_700_000_000L, 123_456_789L)); + richB.addLogicalTypeField("f_dur", new NanosDuration()); + richVals.add(Duration.ofSeconds(42, 999)); + richB.addArrayField("f_slist", FieldType.STRING); + richVals.add(Arrays.asList("a", "b")); + richB.addArrayField("f_ilist", FieldType.INT32); + richVals.add(Arrays.asList(1, 2, 3)); + richB.addArrayField("f_llist", FieldType.INT64); + richVals.add(Arrays.asList(10L, 20L)); + richB.addArrayField("f_dlist", FieldType.DOUBLE); + richVals.add(Arrays.asList(1.5, 2.5)); + richB.addArrayField("f_rlist", FieldType.row(nestedS)); + richVals.add( + Arrays.asList( + Row.withSchema(nestedS).addValues("n1", 1).build(), + Row.withSchema(nestedS).addValues("n2", 2).build())); + richB.addMapField("f_slmap", FieldType.STRING, FieldType.INT64); + richVals.add(ImmutableMap.of("x", 10L)); + richB.addMapField("f_ssmap", FieldType.STRING, FieldType.STRING); + richVals.add(ImmutableMap.of("y", "z")); + richB.addRowField("f_row", nestedS); + richVals.add(Row.withSchema(nestedS).addValues("inner", 99).build()); + richB.addArrayField("f_other", FieldType.STRING.withNullable(true)); + richVals.add(Arrays.asList("ok", null, "tail")); + for (int i = richVals.size(); i < 70; i++) { + richB.addNullableStringField("pad_" + i); + richVals.add((i % 11 == 0) ? null : ("p-" + i)); + } + Schema richS = richB.build(); + RowCoder richC = RowCoder.of(richS); + assertTrue(RowCoderGenerator.hasGeneratedFieldCodec(RowCoderGenerator.generate(richS))); + Row richR = Row.withSchema(richS).attachValues(richVals); + byte[] richBytes = encode(richC, richR); + assertEquals(richR, richC.decode(new ByteArrayInputStream(richBytes))); + assertEquals(richBytes.length, observeSize(richC, richR)); + + // Non-identity encoding positions on wide 70-field chunked coder and 1050-field loop fallback. + for (int width : new int[] {70, 1050}) { + Schema s = buildWideSchema(width, true, false); + Map reversed = new HashMap<>(); + for (int i = 0; i < width; i++) { + reversed.put("f_" + i, width - 1 - i); + } + RowCoderGenerator.overrideEncodingPositions(Objects.requireNonNull(s.getUUID()), reversed); + RowCoder c = RowCoder.of(s); + Row arrRow = buildWideRow(s, true, true); + Row listRow = buildWideRow(s, true, false); + byte[] bArr = encode(c, arrRow); + byte[] bList = encode(c, listRow); + assertArrayEquals(bArr, bList); + assertEquals(arrRow, c.decode(new ByteArrayInputStream(bArr))); + assertEquals(bArr.length, observeSize(c, arrRow)); + } + + // Shrinking evolution (300 -> 200 with nullByteLen == 0 and > 0) and early-null nullByteLen<=8. + Schema s200 = buildWideSchema(200, true, false); + Schema s300 = buildWideSchema(300, true, false); + Row row300NoNull = buildWideRow(s300, false, true); + byte[] b300NoNull = encode(RowCoder.of(s300), row300NoNull); + Row dec200NoNull = RowCoder.of(s200).decode(new ByteArrayInputStream(b300NoNull)); + assertEquals(200, dec200NoNull.getFieldCount()); + assertEquals(row300NoNull.getInt32(0), dec200NoNull.getInt32(0)); + Row row300Sparse = buildWideRow(s300, true, true); + byte[] b300Sparse = encode(RowCoder.of(s300), row300Sparse); + Row dec200Sparse = RowCoder.of(s200).decode(new ByteArrayInputStream(b300Sparse)); + assertNull(dec200Sparse.getValue(0)); + assertEquals(row300Sparse.getInt64(1), dec200Sparse.getInt64(1)); + // Early-only null (field 1 null -> nullByteLen == 1 <= 8 on a 300-field chunked coder). + Object[] earlyNullVals = new Object[300]; + for (int i = 0; i < 300; i++) { + earlyNullVals[i] = row300NoNull.getValue(i); + } + earlyNullVals[1] = null; + Row earlyNullRow = Row.attachValues(s300, earlyNullVals); + byte[] earlyNullBytes = encode(RowCoder.of(s300), earlyNullRow); + assertEquals(earlyNullRow, RowCoder.of(s300).decode(new ByteArrayInputStream(earlyNullBytes))); + // Growing evolution with nullByteLen == 0 (200 -> 300). + Row row200NoNull = buildWideRow(s200, false, true); + byte[] b200NoNull = encode(RowCoder.of(s200), row200NoNull); + Row dec300From200 = RowCoder.of(s300).decode(new ByteArrayInputStream(b200NoNull)); + assertEquals(row200NoNull.getInt32(0), dec300From200.getInt32(0)); + assertNull(dec300From200.getValue(250)); + + // >4096 fields (4200 fields -> 525-byte null bitmap > SCRATCH_SIZE) with reversed positions. + Schema.Builder hugeB = Schema.builder(); + Object[] hugeArr = new Object[4200]; + Map hugePos = new HashMap<>(4200 * 2); + for (int i = 0; i < 4200; i++) { + hugeB.addNullableInt32Field("h_" + i); + hugeArr[i] = (i == 0 || i == 2000 || i == 4199) ? null : i; + hugePos.put("h_" + i, 4199 - i); + } + Schema hugeS = hugeB.build(); + RowCoderGenerator.overrideEncodingPositions(Objects.requireNonNull(hugeS.getUUID()), hugePos); + RowCoder hugeC = RowCoder.of(hugeS); + Row hugeArrRow = Row.attachValues(hugeS, hugeArr); + Row hugeListRow = Row.withSchema(hugeS).attachValues(new ArrayList<>(Arrays.asList(hugeArr))); + byte[] hugeBytesArr = encode(hugeC, hugeArrRow); + byte[] hugeBytesList = encode(hugeC, hugeListRow); + assertArrayEquals(hugeBytesArr, hugeBytesList); + assertEquals(hugeArrRow, hugeC.decode(new ByteArrayInputStream(hugeBytesArr))); + assertEquals(hugeBytesArr.length, observeSize(hugeC, hugeArrRow)); + } + + /** 68-field strictly non-nullable JavaBean exercising !nullableHeader && !isPojo chunked code. */ + @DefaultSchema(JavaBeanSchema.class) + public static class Wide68NonNullBean { + private int i00, i01, i02, i03, i04, i05, i06, i07, i08, i09; + private int i10, i11, i12, i13, i14, i15, i16, i17, i18, i19; + private int i20, i21, i22, i23, i24, i25, i26, i27, i28, i29; + private int i30, i31, i32, i33; + private String s00 = "", s01 = "", s02 = "", s03 = "", s04 = "", s05 = "", s06 = "", s07 = ""; + private String s08 = "", s09 = "", s10 = "", s11 = "", s12 = "", s13 = "", s14 = "", s15 = ""; + private String s16 = "", s17 = "", s18 = "", s19 = "", s20 = "", s21 = "", s22 = "", s23 = ""; + private String s24 = "", s25 = "", s26 = "", s27 = "", s28 = "", s29 = "", s30 = "", s31 = ""; + private String s32 = "", s33 = ""; + + public Wide68NonNullBean() {} + + static Wide68NonNullBean sample() { + Wide68NonNullBean b = new Wide68NonNullBean(); + b.i00 = 1; + b.i33 = 34; + b.s00 = "first"; + b.s33 = "last"; + return b; + } + + public int getI00() { + return i00; + } + + public void setI00(int v) { + i00 = v; + } + + public int getI01() { + return i01; + } + + public void setI01(int v) { + i01 = v; + } + + public int getI02() { + return i02; + } + + public void setI02(int v) { + i02 = v; + } + + public int getI03() { + return i03; + } + + public void setI03(int v) { + i03 = v; + } + + public int getI04() { + return i04; + } + + public void setI04(int v) { + i04 = v; + } + + public int getI05() { + return i05; + } + + public void setI05(int v) { + i05 = v; + } + + public int getI06() { + return i06; + } + + public void setI06(int v) { + i06 = v; + } + + public int getI07() { + return i07; + } + + public void setI07(int v) { + i07 = v; + } + + public int getI08() { + return i08; + } + + public void setI08(int v) { + i08 = v; + } + + public int getI09() { + return i09; + } + + public void setI09(int v) { + i09 = v; + } + + public int getI10() { + return i10; + } + + public void setI10(int v) { + i10 = v; + } + + public int getI11() { + return i11; + } + + public void setI11(int v) { + i11 = v; + } + + public int getI12() { + return i12; + } + + public void setI12(int v) { + i12 = v; + } + + public int getI13() { + return i13; + } + + public void setI13(int v) { + i13 = v; + } + + public int getI14() { + return i14; + } + + public void setI14(int v) { + i14 = v; + } + + public int getI15() { + return i15; + } + + public void setI15(int v) { + i15 = v; + } + + public int getI16() { + return i16; + } + + public void setI16(int v) { + i16 = v; + } + + public int getI17() { + return i17; + } + + public void setI17(int v) { + i17 = v; + } + + public int getI18() { + return i18; + } + + public void setI18(int v) { + i18 = v; + } + + public int getI19() { + return i19; + } + + public void setI19(int v) { + i19 = v; + } + + public int getI20() { + return i20; + } + + public void setI20(int v) { + i20 = v; + } + + public int getI21() { + return i21; + } + + public void setI21(int v) { + i21 = v; + } + + public int getI22() { + return i22; + } + + public void setI22(int v) { + i22 = v; + } + + public int getI23() { + return i23; + } + + public void setI23(int v) { + i23 = v; + } + + public int getI24() { + return i24; + } + + public void setI24(int v) { + i24 = v; + } + + public int getI25() { + return i25; + } + + public void setI25(int v) { + i25 = v; + } + + public int getI26() { + return i26; + } + + public void setI26(int v) { + i26 = v; + } + + public int getI27() { + return i27; + } + + public void setI27(int v) { + i27 = v; + } + + public int getI28() { + return i28; + } + + public void setI28(int v) { + i28 = v; + } + + public int getI29() { + return i29; + } + + public void setI29(int v) { + i29 = v; + } + + public int getI30() { + return i30; + } + + public void setI30(int v) { + i30 = v; + } + + public int getI31() { + return i31; + } + + public void setI31(int v) { + i31 = v; + } + + public int getI32() { + return i32; + } + + public void setI32(int v) { + i32 = v; + } + + public int getI33() { + return i33; + } + + public void setI33(int v) { + i33 = v; + } + + public String getS00() { + return s00; + } + + public void setS00(String v) { + s00 = v; + } + + public String getS01() { + return s01; + } + + public void setS01(String v) { + s01 = v; + } + + public String getS02() { + return s02; + } + + public void setS02(String v) { + s02 = v; + } + + public String getS03() { + return s03; + } + + public void setS03(String v) { + s03 = v; + } + + public String getS04() { + return s04; + } + + public void setS04(String v) { + s04 = v; + } + + public String getS05() { + return s05; + } + + public void setS05(String v) { + s05 = v; + } + + public String getS06() { + return s06; + } + + public void setS06(String v) { + s06 = v; + } + + public String getS07() { + return s07; + } + + public void setS07(String v) { + s07 = v; + } + + public String getS08() { + return s08; + } + + public void setS08(String v) { + s08 = v; + } + + public String getS09() { + return s09; + } + + public void setS09(String v) { + s09 = v; + } + + public String getS10() { + return s10; + } + + public void setS10(String v) { + s10 = v; + } + + public String getS11() { + return s11; + } + + public void setS11(String v) { + s11 = v; + } + + public String getS12() { + return s12; + } + + public void setS12(String v) { + s12 = v; + } + + public String getS13() { + return s13; + } + + public void setS13(String v) { + s13 = v; + } + + public String getS14() { + return s14; + } + + public void setS14(String v) { + s14 = v; + } + + public String getS15() { + return s15; + } + + public void setS15(String v) { + s15 = v; + } + + public String getS16() { + return s16; + } + + public void setS16(String v) { + s16 = v; + } + + public String getS17() { + return s17; + } + + public void setS17(String v) { + s17 = v; + } + + public String getS18() { + return s18; + } + + public void setS18(String v) { + s18 = v; + } + + public String getS19() { + return s19; + } + + public void setS19(String v) { + s19 = v; + } + + public String getS20() { + return s20; + } + + public void setS20(String v) { + s20 = v; + } + + public String getS21() { + return s21; + } + + public void setS21(String v) { + s21 = v; + } + + public String getS22() { + return s22; + } + + public void setS22(String v) { + s22 = v; + } + + public String getS23() { + return s23; + } + + public void setS23(String v) { + s23 = v; + } + + public String getS24() { + return s24; + } + + public void setS24(String v) { + s24 = v; + } + + public String getS25() { + return s25; + } + + public void setS25(String v) { + s25 = v; + } + + public String getS26() { + return s26; + } + + public void setS26(String v) { + s26 = v; + } + + public String getS27() { + return s27; + } + + public void setS27(String v) { + s27 = v; + } + + public String getS28() { + return s28; + } + + public void setS28(String v) { + s28 = v; + } + + public String getS29() { + return s29; + } + + public void setS29(String v) { + s29 = v; + } + + public String getS30() { + return s30; + } + + public void setS30(String v) { + s30 = v; + } + + public String getS31() { + return s31; + } + + public void setS31(String v) { + s31 = v; + } + + public String getS32() { + return s32; + } + + public void setS32(String v) { + s32 = v; + } + + public String getS33() { + return s33; + } + + public void setS33(String v) { + s33 = v; + } + } + + /** + * 68-field strictly non-nullable POJO exercising !nullableHeader, staticEncoding, and IsCheap. + */ + @DefaultSchema(JavaFieldSchema.class) + public static class Wide68NonNullPojo { + public byte fByte = 3; + public short fShort = -12; + public int fInt = 1000; + public long fLong = 1_000_000_000L; + public float fFloat = 2.5f; + public double fDouble = 3.25; + public boolean fBool = true; + public String fStr = "hello"; + public byte[] fBytes = new byte[] {1, 2, 3}; + public BigDecimal fDec = new BigDecimal("12.34"); + public LocalDate fDate = LocalDate.of(2026, 1, 2); + public Status fStatus = Status.ACTIVE; + public java.util.Collection fTags = Arrays.asList("t1", "t2"); + public java.util.Collection fItems = + Collections.singletonList(new NestedItem("item", 2, 4.5)); + public NestedItem fNested = new NestedItem("nested", 7, 8.5); + public int p00, p01, p02, p03, p04, p05, p06, p07, p08, p09; + public int p10, p11, p12, p13, p14, p15, p16, p17, p18, p19; + public int p20, p21, p22, p23, p24, p25, p26, p27, p28, p29; + public int p30, p31, p32, p33, p34, p35, p36, p37, p38, p39; + public int p40, p41, p42, p43, p44, p45, p46, p47, p48, p49; + public int p50, p51, p52; + + public Wide68NonNullPojo() {} + } + + /** 68-field all-primitive POJO exercising !needsScratch decode and O(1) !anyNeedsIsCheap. */ + @DefaultSchema(JavaFieldSchema.class) + public static class Wide68PrimitivesPojo { + public int i00, i01, i02, i03, i04, i05, i06, i07, i08, i09; + public int i10, i11, i12, i13, i14, i15, i16, i17, i18, i19; + public int i20, i21, i22, i23, i24, i25, i26, i27, i28, i29; + public int i30, i31, i32, i33; + public long l00, l01, l02, l03, l04, l05, l06, l07, l08, l09; + public long l10, l11, l12, l13, l14, l15, l16, l17, l18, l19; + public long l20, l21, l22, l23, l24, l25, l26, l27, l28, l29; + public long l30, l31, l32, l33; + + public Wide68PrimitivesPojo() {} + } + + /** + * 68-field nullable POJO with Map/String/Nested to test IsCheapChunkImpl Map & SUB_ROW branches. + */ + @DefaultSchema(JavaFieldSchema.class) + public static class Wide68MapNullablePojo { + public @Nullable Map fMap; + public @Nullable String fStr; + public @Nullable NestedItem fNested; + public @Nullable Integer fBoxInt; + public int p00, p01, p02, p03, p04, p05, p06, p07, p08, p09; + public int p10, p11, p12, p13, p14, p15, p16, p17, p18, p19; + public int p20, p21, p22, p23, p24, p25, p26, p27, p28, p29; + public int p30, p31, p32, p33, p34, p35, p36, p37, p38, p39; + public int p40, p41, p42, p43, p44, p45, p46, p47, p48, p49; + public int p50, p51, p52, p53, p54, p55, p56, p57, p58, p59; + public int p60, p61, p62, p63; + + public Wide68MapNullablePojo() {} + } + + /** 520-field POJO exceeding MAX_CHUNKED_DIRECT_FIELDS (512) to verify clean fallback. */ + @DefaultSchema(JavaFieldSchema.class) + public static class Wide520Pojo { + public int f000, + f001, + f002, + f003, + f004, + f005, + f006, + f007, + f008, + f009, + f010, + f011, + f012, + f013, + f014, + f015, + f016, + f017, + f018, + f019; + public int f020, + f021, + f022, + f023, + f024, + f025, + f026, + f027, + f028, + f029, + f030, + f031, + f032, + f033, + f034, + f035, + f036, + f037, + f038, + f039; + public int f040, + f041, + f042, + f043, + f044, + f045, + f046, + f047, + f048, + f049, + f050, + f051, + f052, + f053, + f054, + f055, + f056, + f057, + f058, + f059; + public int f060, + f061, + f062, + f063, + f064, + f065, + f066, + f067, + f068, + f069, + f070, + f071, + f072, + f073, + f074, + f075, + f076, + f077, + f078, + f079; + public int f080, + f081, + f082, + f083, + f084, + f085, + f086, + f087, + f088, + f089, + f090, + f091, + f092, + f093, + f094, + f095, + f096, + f097, + f098, + f099; + public int f100, + f101, + f102, + f103, + f104, + f105, + f106, + f107, + f108, + f109, + f110, + f111, + f112, + f113, + f114, + f115, + f116, + f117, + f118, + f119; + public int f120, + f121, + f122, + f123, + f124, + f125, + f126, + f127, + f128, + f129, + f130, + f131, + f132, + f133, + f134, + f135, + f136, + f137, + f138, + f139; + public int f140, + f141, + f142, + f143, + f144, + f145, + f146, + f147, + f148, + f149, + f150, + f151, + f152, + f153, + f154, + f155, + f156, + f157, + f158, + f159; + public int f160, + f161, + f162, + f163, + f164, + f165, + f166, + f167, + f168, + f169, + f170, + f171, + f172, + f173, + f174, + f175, + f176, + f177, + f178, + f179; + public int f180, + f181, + f182, + f183, + f184, + f185, + f186, + f187, + f188, + f189, + f190, + f191, + f192, + f193, + f194, + f195, + f196, + f197, + f198, + f199; + public int f200, + f201, + f202, + f203, + f204, + f205, + f206, + f207, + f208, + f209, + f210, + f211, + f212, + f213, + f214, + f215, + f216, + f217, + f218, + f219; + public int f220, + f221, + f222, + f223, + f224, + f225, + f226, + f227, + f228, + f229, + f230, + f231, + f232, + f233, + f234, + f235, + f236, + f237, + f238, + f239; + public int f240, + f241, + f242, + f243, + f244, + f245, + f246, + f247, + f248, + f249, + f250, + f251, + f252, + f253, + f254, + f255, + f256, + f257, + f258, + f259; + public int f260, + f261, + f262, + f263, + f264, + f265, + f266, + f267, + f268, + f269, + f270, + f271, + f272, + f273, + f274, + f275, + f276, + f277, + f278, + f279; + public int f280, + f281, + f282, + f283, + f284, + f285, + f286, + f287, + f288, + f289, + f290, + f291, + f292, + f293, + f294, + f295, + f296, + f297, + f298, + f299; + public int f300, + f301, + f302, + f303, + f304, + f305, + f306, + f307, + f308, + f309, + f310, + f311, + f312, + f313, + f314, + f315, + f316, + f317, + f318, + f319; + public int f320, + f321, + f322, + f323, + f324, + f325, + f326, + f327, + f328, + f329, + f330, + f331, + f332, + f333, + f334, + f335, + f336, + f337, + f338, + f339; + public int f340, + f341, + f342, + f343, + f344, + f345, + f346, + f347, + f348, + f349, + f350, + f351, + f352, + f353, + f354, + f355, + f356, + f357, + f358, + f359; + public int f360, + f361, + f362, + f363, + f364, + f365, + f366, + f367, + f368, + f369, + f370, + f371, + f372, + f373, + f374, + f375, + f376, + f377, + f378, + f379; + public int f380, + f381, + f382, + f383, + f384, + f385, + f386, + f387, + f388, + f389, + f390, + f391, + f392, + f393, + f394, + f395, + f396, + f397, + f398, + f399; + public int f400, + f401, + f402, + f403, + f404, + f405, + f406, + f407, + f408, + f409, + f410, + f411, + f412, + f413, + f414, + f415, + f416, + f417, + f418, + f419; + public int f420, + f421, + f422, + f423, + f424, + f425, + f426, + f427, + f428, + f429, + f430, + f431, + f432, + f433, + f434, + f435, + f436, + f437, + f438, + f439; + public int f440, + f441, + f442, + f443, + f444, + f445, + f446, + f447, + f448, + f449, + f450, + f451, + f452, + f453, + f454, + f455, + f456, + f457, + f458, + f459; + public int f460, + f461, + f462, + f463, + f464, + f465, + f466, + f467, + f468, + f469, + f470, + f471, + f472, + f473, + f474, + f475, + f476, + f477, + f478, + f479; + public int f480, + f481, + f482, + f483, + f484, + f485, + f486, + f487, + f488, + f489, + f490, + f491, + f492, + f493, + f494, + f495, + f496, + f497, + f498, + f499; + public int f500, + f501, + f502, + f503, + f504, + f505, + f506, + f507, + f508, + f509, + f510, + f511, + f512, + f513, + f514, + f515, + f516, + f517, + f518, + f519; + + public Wide520Pojo() {} + } + + @Test + public void testChunkedDirectSchemaCoderNonNullableStaticRichEvolutionAndErrors() + throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder coder = registry.getSchemaCoder(Wide68NonNullPojo.class); + assertEquals(68, coder.getSchema().getFieldCount()); + assertFalse(coder.getSchema().hasNullableFields()); + assertTrue(coder.hasDirectCoder()); + + Wide68NonNullPojo sample = new Wide68NonNullPojo(); + sample.p52 = 999; + RowCoder rowCoder = RowCoder.of(coder.getSchema()); + byte[] directBytes = encode(coder, sample); + Row asRow = coder.getToRowFunction().apply(sample); + assertArrayEquals(encode(rowCoder, asRow), directBytes); + assertEquals(directBytes.length, observeSize(coder, sample)); + assertEquals( + asRow, coder.getToRowFunction().apply(coder.decode(new ByteArrayInputStream(directBytes)))); + + // IsCheapChunkImpl: ArrayList -> false; CountingObservableCollection -> true & lazy; + // long String (>1024) -> false; nested long String -> false; null -> false. + assertFalse(coder.isRegisterByteSizeObserverCheap(null)); + assertFalse(coder.isRegisterByteSizeObserverCheap(sample)); + sample.fTags = new CountingObservableCollection<>(Arrays.asList("a", "b")); + sample.fItems = new CountingObservableCollection<>(Collections.singletonList(sample.fNested)); + assertTrue(coder.isRegisterByteSizeObserverCheap(sample)); + ElementByteSizeObserver lazyObs = + new ElementByteSizeObserver() { + @Override + protected void reportElementSize(long elementByteSize) {} + }; + coder.registerByteSizeObserver(sample, lazyObs); + assertTrue(lazyObs.getIsLazy()); + + StringBuilder sb = new StringBuilder(1100); + for (int i = 0; i < 1100; i++) { + sb.append('x'); + } + sample.fStr = sb.toString(); + assertFalse(coder.isRegisterByteSizeObserverCheap(sample)); + sample.fStr = "short"; + sample.fNested = new NestedItem(sb.toString(), 1, 1.0); + assertFalse(coder.isRegisterByteSizeObserverCheap(sample)); + sample.fNested = new NestedItem("ok", 1, 1.0); + + // Null in non-nullable reference field throws RuntimeException in encode and byteSize. + sample.fStr = null; + assertThrows(RuntimeException.class, () -> encode(coder, sample)); + assertThrows(RuntimeException.class, () -> observeSize(coder, sample)); + sample.fStr = "restored"; + + // Null top-level value throws CoderException in encode and registerByteSizeObserver. + assertThrows(CoderException.class, () -> encode(coder, null)); + assertThrows(CoderException.class, () -> observeSize(coder, null)); + + // Negative nullByteLen throws CoderException. + ByteArrayOutputStream negNullStream = new ByteArrayOutputStream(); + VarInt.encode(68, negNullStream); + VarInt.encode(-1, negNullStream); + assertThrows( + CoderException.class, + () -> coder.decode(new ByteArrayInputStream(negNullStream.toByteArray()))); + + // Non-nullable wide POJO decoding a stream with nullByteLen > 0 hits decodeEvolvedAfterNullLen. + Wide68NonNullPojo freshSample = new Wide68NonNullPojo(); + freshSample.p52 = 999; + byte[] freshBytes = encode(coder, freshSample); + ByteArrayOutputStream withEmptyNonZeroBitmap = new ByteArrayOutputStream(); + VarInt.encode(68, withEmptyNonZeroBitmap); + VarInt.encode(1, withEmptyNonZeroBitmap); + withEmptyNonZeroBitmap.write(0); // 1-byte all-zero bitmap + byte[] rawNoHeader = Arrays.copyOfRange(freshBytes, 2, freshBytes.length); + withEmptyNonZeroBitmap.write(rawNoHeader); + Wide68NonNullPojo evolvedNullBitmap = + coder.decode(new ByteArrayInputStream(withEmptyNonZeroBitmap.toByteArray())); + assertEquals( + coder.getToRowFunction().apply(freshSample), + coder.getToRowFunction().apply(evolvedNullBitmap)); + + // Wide staticEncoding DirectSchemaCoder + encoding position override. + JavaFieldSchema provider = new JavaFieldSchema(); + Schema staticSchema = + Schema.builder() + .addFields(coder.getSchema().getFields()) + .setOptions( + Schema.Options.builder() + .setOption("beam:option:row:static_encoding", FieldType.BOOLEAN, true) + .build()) + .build(); + SchemaCoder staticCoder = + SchemaCoder.of( + staticSchema, + TypeDescriptor.of(Wide68NonNullPojo.class), + provider + .new ToRowWithValueGetters<>(staticSchema, TypeDescriptor.of(Wide68NonNullPojo.class)), + provider.fromRowFunction(TypeDescriptor.of(Wide68NonNullPojo.class))); + assertTrue(staticCoder.hasDirectCoder()); + byte[] staticDirect = encode(staticCoder, freshSample); + byte[] staticRow = + encode(RowCoder.of(staticSchema), staticCoder.getToRowFunction().apply(freshSample)); + assertArrayEquals(staticRow, staticDirect); + assertEquals(staticDirect.length, observeSize(staticCoder, freshSample)); + assertEquals( + staticCoder.getToRowFunction().apply(freshSample), + staticCoder + .getToRowFunction() + .apply(staticCoder.decode(new ByteArrayInputStream(staticDirect)))); + + Schema reorderedSchema = Schema.builder().addFields(coder.getSchema().getFields()).build(); + Map revPos = new HashMap<>(); + for (int i = 0; i < 68; i++) { + revPos.put(reorderedSchema.getField(i).getName(), 67 - i); + } + RowCoderGenerator.overrideEncodingPositions( + Objects.requireNonNull(reorderedSchema.getUUID()), revPos); + SchemaCoder reorderedCoder = + SchemaCoder.of( + reorderedSchema, + TypeDescriptor.of(Wide68NonNullPojo.class), + provider + .new ToRowWithValueGetters<>( + reorderedSchema, TypeDescriptor.of(Wide68NonNullPojo.class)), + provider.fromRowFunction(TypeDescriptor.of(Wide68NonNullPojo.class))); + assertTrue(reorderedCoder.hasDirectCoder()); + byte[] reordDirect = encode(reorderedCoder, freshSample); + assertArrayEquals( + encode(RowCoder.of(reorderedSchema), reorderedCoder.getToRowFunction().apply(freshSample)), + reordDirect); + assertEquals( + reorderedCoder.getToRowFunction().apply(freshSample), + reorderedCoder + .getToRowFunction() + .apply(reorderedCoder.decode(new ByteArrayInputStream(reordDirect)))); + + // All-primitive wide POJO (!needsScratch decode & O(1) !anyNeedsIsCheap). + SchemaCoder primCoder = + registry.getSchemaCoder(Wide68PrimitivesPojo.class); + assertTrue(primCoder.hasDirectCoder()); + Wide68PrimitivesPojo prim = new Wide68PrimitivesPojo(); + prim.i00 = 11; + prim.i33 = -22; + prim.l00 = 1_000_000_000L; + prim.l33 = -99L; + assertTrue(primCoder.isRegisterByteSizeObserverCheap(prim)); + assertFalse(primCoder.isRegisterByteSizeObserverCheap(null)); + byte[] primBytes = encode(primCoder, prim); + assertEquals(primBytes.length, observeSize(primCoder, prim)); + assertEquals( + primCoder.getToRowFunction().apply(prim), + primCoder.getToRowFunction().apply(primCoder.decode(new ByteArrayInputStream(primBytes)))); + + // Nullable Map + SUB_ROW IsCheapChunkImpl & evolution/primitive-null/truncated-stream errors. + SchemaCoder mapCoder = + registry.getSchemaCoder(Wide68MapNullablePojo.class); + assertTrue(mapCoder.hasDirectCoder()); + Wide68MapNullablePojo mp = new Wide68MapNullablePojo(); + assertTrue(mapCoder.isRegisterByteSizeObserverCheap(mp)); + mp.fMap = ImmutableMap.of("k", 7L); + assertFalse(mapCoder.isRegisterByteSizeObserverCheap(mp)); + byte[] mpBytes = encode(mapCoder, mp); + assertEquals(mpBytes.length, observeSize(mapCoder, mp)); + assertEquals( + mapCoder.getToRowFunction().apply(mp), + mapCoder.getToRowFunction().apply(mapCoder.decode(new ByteArrayInputStream(mpBytes)))); + + // Schema evolution on chunked DirectSchemaCoder: stream with 69 fields (extra trailing int). + Schema s69 = + Schema.builder() + .addFields(mapCoder.getSchema().getFields()) + .addInt32Field("extra_69") + .build(); + Object[] vals69 = new Object[69]; + Row mpRow = mapCoder.getToRowFunction().apply(mp); + for (int i = 0; i < 68; i++) { + vals69[i] = mpRow.getValue(i); + } + vals69[68] = 777; + byte[] bytes69 = encode(RowCoder.of(s69), Row.attachValues(s69, vals69)); + Wide68MapNullablePojo decFrom69 = mapCoder.decode(new ByteArrayInputStream(bytes69)); + assertEquals(mpRow, mapCoder.getToRowFunction().apply(decFrom69)); + + // Wide non-nullable JavaBean (!nullableHeader && !isPojo) normal + staticEncoding. + SchemaCoder nnBeanCoder = registry.getSchemaCoder(Wide68NonNullBean.class); + assertEquals(68, nnBeanCoder.getSchema().getFieldCount()); + assertFalse(nnBeanCoder.getSchema().hasNullableFields()); + assertTrue(nnBeanCoder.hasDirectCoder()); + Wide68NonNullBean nnBean = Wide68NonNullBean.sample(); + byte[] nnBeanBytes = encode(nnBeanCoder, nnBean); + Row nnBeanRow = nnBeanCoder.getToRowFunction().apply(nnBean); + assertArrayEquals(encode(RowCoder.of(nnBeanCoder.getSchema()), nnBeanRow), nnBeanBytes); + assertEquals(nnBeanBytes.length, observeSize(nnBeanCoder, nnBean)); + assertEquals( + nnBeanRow, + nnBeanCoder + .getToRowFunction() + .apply(nnBeanCoder.decode(new ByteArrayInputStream(nnBeanBytes)))); + + JavaBeanSchema beanProvider = new JavaBeanSchema(); + Schema staticBeanSchema = + Schema.builder() + .addFields(nnBeanCoder.getSchema().getFields()) + .setOptions( + Schema.Options.builder() + .setOption("beam:option:row:static_encoding", FieldType.BOOLEAN, true) + .build()) + .build(); + SchemaCoder staticBeanCoder = + SchemaCoder.of( + staticBeanSchema, + TypeDescriptor.of(Wide68NonNullBean.class), + beanProvider + .new ToRowWithValueGetters<>( + staticBeanSchema, TypeDescriptor.of(Wide68NonNullBean.class)), + beanProvider.fromRowFunction(TypeDescriptor.of(Wide68NonNullBean.class))); + assertTrue(staticBeanCoder.hasDirectCoder()); + byte[] staticBeanBytes = encode(staticBeanCoder, nnBean); + assertArrayEquals( + encode(RowCoder.of(staticBeanSchema), staticBeanCoder.getToRowFunction().apply(nnBean)), + staticBeanBytes); + assertEquals( + staticBeanCoder.getToRowFunction().apply(nnBean), + staticBeanCoder + .getToRowFunction() + .apply(staticBeanCoder.decode(new ByteArrayInputStream(staticBeanBytes)))); + + // Bit-31 null, streamFieldCount < count evolution (139 -> 140), primitive null -> NPE, + // truncated stream -> CoderException, and clone on Wide140Pojo. + SchemaCoder wide140Coder = + SerializableUtils.clone(registry.getSchemaCoder(Wide140Pojo.class)); + assertTrue(wide140Coder.hasDirectCoder()); + Wide140Pojo bit31Pojo = Wide140Pojo.sample(false); + bit31Pojo.s22 = null; // pos 127 = chunk 3 bit 31 + byte[] b140 = encode(wide140Coder, bit31Pojo); + Wide140Pojo d140 = wide140Coder.decode(new ByteArrayInputStream(b140)); + assertNull(d140.s22); + assertEquals( + wide140Coder.getToRowFunction().apply(bit31Pojo), + wide140Coder.getToRowFunction().apply(d140)); + // Growing evolution (139-field stream decoded by 140-field chunked DirectSchemaCoder). + Schema s139 = + Schema.builder().addFields(wide140Coder.getSchema().getFields().subList(0, 139)).build(); + Row row140 = wide140Coder.getToRowFunction().apply(bit31Pojo); + Object[] vals139 = new Object[139]; + for (int i = 0; i < 139; i++) { + vals139[i] = row140.getValue(i); + } + byte[] bytes139 = encode(RowCoder.of(s139), Row.attachValues(s139, vals139)); + Wide140Pojo decFrom139 = wide140Coder.decode(new ByteArrayInputStream(bytes139)); + assertNull(decFrom139.s34); + assertEquals(bit31Pojo.i00, decFrom139.i00); + assertEquals(bit31Pojo.s33, decFrom139.s33); + // Truncated stream exercises catch0/catch1 scratch release. + assertThrows( + CoderException.class, + () -> wide140Coder.decode(new ByteArrayInputStream(Arrays.copyOf(b140, 20)))); + // Null bit set on primitive field 0 (i00) throws NullPointerException (nullPrimitive). + ByteArrayOutputStream primNullStream = new ByteArrayOutputStream(); + VarInt.encode(140, primNullStream); + VarInt.encode(1, primNullStream); + primNullStream.write(0x01); // field 0 (primitive int i00) marked null + assertThrows( + NullPointerException.class, + () -> wide140Coder.decode(new ByteArrayInputStream(primNullStream.toByteArray()))); + + // >512-field POJO falls back cleanly (!hasDirectCoder) and still round-trips. + SchemaCoder wide520Coder = registry.getSchemaCoder(Wide520Pojo.class); + assertEquals(520, wide520Coder.getSchema().getFieldCount()); + assertFalse(wide520Coder.hasDirectCoder()); + Wide520Pojo p520 = new Wide520Pojo(); + p520.f000 = 123; + p520.f519 = 456; + byte[] b520 = encode(wide520Coder, p520); + Wide520Pojo d520 = wide520Coder.decode(new ByteArrayInputStream(b520)); + assertEquals(123, d520.f000); + assertEquals(456, d520.f519); + } + + /** >128-field POJO without a zero-arg constructor (regression test for T1/C2). */ + @DefaultSchema(JavaFieldSchema.class) + public static class Wide130NoNoArgPojo { + public int f000, f001, f002, f003, f004, f005, f006, f007, f008, f009; + public int f010, f011, f012, f013, f014, f015, f016, f017, f018, f019; + public int f020, f021, f022, f023, f024, f025, f026, f027, f028, f029; + public int f030, f031, f032, f033, f034, f035, f036, f037, f038, f039; + public int f040, f041, f042, f043, f044, f045, f046, f047, f048, f049; + public int f050, f051, f052, f053, f054, f055, f056, f057, f058, f059; + public int f060, f061, f062, f063, f064, f065, f066, f067, f068, f069; + public int f070, f071, f072, f073, f074, f075, f076, f077, f078, f079; + public int f080, f081, f082, f083, f084, f085, f086, f087, f088, f089; + public int f090, f091, f092, f093, f094, f095, f096, f097, f098, f099; + public int f100, f101, f102, f103, f104, f105, f106, f107, f108, f109; + public int f110, f111, f112, f113, f114, f115, f116, f117, f118, f119; + public int f120, f121, f122, f123, f124, f125, f126, f127, f128, f129; + + public Wide130NoNoArgPojo(int x) { + this.f000 = x; + } + } + + public static class Wide130RichBase { + public byte baseByte; + public short baseShort; + public float baseFloat; + public boolean baseBool; + public @Nullable Integer baseBoxInt; + } + + /** + * >128-field POJO subclass with inherited fields, all primitives, and non-trivial setter types. + */ + @DefaultSchema(JavaFieldSchema.class) + public static class Wide130RichSubPojo extends Wide130RichBase { + public byte[] fBytes; + public LocalDate fDate; + public Status fStatus; + public List fList; + public Map fMap; + public NestedItem fNested; + public @Nullable String fNullStr; + public int p000, p001, p002, p003, p004, p005, p006, p007, p008, p009; + public int p010, p011, p012, p013, p014, p015, p016, p017, p018, p019; + public int p020, p021, p022, p023, p024, p025, p026, p027, p028, p029; + public int p030, p031, p032, p033, p034, p035, p036, p037, p038, p039; + public int p040, p041, p042, p043, p044, p045, p046, p047, p048, p049; + public int p050, p051, p052, p053, p054, p055, p056, p057, p058, p059; + public int p060, p061, p062, p063, p064, p065, p066, p067, p068, p069; + public int p070, p071, p072, p073, p074, p075, p076, p077, p078, p079; + public int p080, p081, p082, p083, p084, p085, p086, p087, p088, p089; + public int p090, p091, p092, p093, p094, p095, p096, p097, p098, p099; + public int p100, p101, p102, p103, p104, p105, p106, p107, p108, p109; + public int p110, p111, p112, p113, p114, p115, p116, p117; + + public Wide130RichSubPojo() {} + } + + @Test + public void testChunkedPojoCreatorMissingNoArgAndRichSubclass130Fields() throws Exception { + SchemaRegistry registry = SchemaRegistry.createDefault(); + Schema noNoArgSchema = registry.getSchema(Wide130NoNoArgPojo.class); + Object[] zeros = new Object[130]; + Arrays.fill(zeros, 0); + Row noNoArgRow = Row.attachValues(noNoArgSchema, zeros); + RuntimeException ex = + assertThrows( + RuntimeException.class, + () -> registry.getFromRowFunction(Wide130NoNoArgPojo.class).apply(noNoArgRow)); + assertTrue( + "Expected descriptive zero-arg constructor message, got: " + ex.getMessage(), + ex.getMessage() != null && ex.getMessage().contains("zero-argument constructor")); + + SchemaCoder coder = registry.getSchemaCoder(Wide130RichSubPojo.class); + assertEquals(130, coder.getSchema().getFieldCount()); + Wide130RichSubPojo orig = new Wide130RichSubPojo(); + orig.baseByte = -9; + orig.baseShort = 321; + orig.baseFloat = 4.25f; + orig.baseBool = true; + orig.baseBoxInt = null; + orig.fBytes = new byte[] {9, 8, 7}; + orig.fDate = LocalDate.of(2026, 7, 4); + orig.fStatus = Status.ACTIVE; + orig.fList = Arrays.asList("one", "two"); + orig.fMap = ImmutableMap.of("m", 42L); + orig.fNested = new NestedItem("sub", 5, 6.5); + orig.fNullStr = null; + orig.p000 = 10; + orig.p117 = 1170; + + Row row = coder.getToRowFunction().apply(orig); + Wide130RichSubPojo recreated = coder.getFromRowFunction().apply(row); + assertEquals(orig.baseByte, recreated.baseByte); + assertEquals(orig.baseShort, recreated.baseShort); + assertEquals(orig.baseFloat, recreated.baseFloat, 0.0f); + assertEquals(orig.baseBool, recreated.baseBool); + assertNull(recreated.baseBoxInt); + assertArrayEquals(orig.fBytes, recreated.fBytes); + assertEquals(orig.fDate, recreated.fDate); + assertEquals(orig.fStatus, recreated.fStatus); + assertEquals(orig.fList, recreated.fList); + assertEquals(orig.fMap, recreated.fMap); + assertEquals(orig.fNested, recreated.fNested); + assertNull(recreated.fNullStr); + assertEquals(10, recreated.p000); + assertEquals(1170, recreated.p117); + } + + @Test + public void testSchemaCompactContainerCacheZeroBit63IterableAndSerialization() { + // 0 container fields: count == 0, valid index -> -1, OOB throws IndexOutOfBoundsException. + Schema noContainers = Schema.builder().addInt32Field("a").addStringField("b").build(); + assertEquals(0, noContainers.getCacheableContainerCount()); + assertEquals(-1, noContainers.getContainerCacheSlot(0)); + assertEquals(-1, noContainers.getContainerCacheSlot(1)); + assertThrows(IndexOutOfBoundsException.class, () -> noContainers.getContainerCacheSlot(-1)); + assertThrows(IndexOutOfBoundsException.class, () -> noContainers.getContainerCacheSlot(2)); + + // Wide 300-field schema with containers at index 0, 5, 63 (bit 63 POPCNT!), 64, and 250. + Schema.Builder b = Schema.builder(); + for (int i = 0; i < 300; i++) { + if (i == 0) { + b.addArrayField("c_0", FieldType.STRING); + } else if (i == 5) { + b.addIterableField("c_5", FieldType.INT32); + } else if (i == 63) { + b.addMapField("c_63", FieldType.STRING, FieldType.INT64); + } else if (i == 64) { + b.addArrayField("c_64", FieldType.STRING); + } else if (i == 250) { + b.addIterableField("c_250", FieldType.STRING); + } else { + b.addInt32Field("f_" + i); + } + } + Schema original = b.build(); + for (Schema s : new Schema[] {original, SerializableUtils.clone(original)}) { + assertEquals(5, s.getCacheableContainerCount()); + assertEquals(0, s.getContainerCacheSlot(0)); + assertEquals(1, s.getContainerCacheSlot(5)); + assertEquals(2, s.getContainerCacheSlot(63)); + assertEquals(3, s.getContainerCacheSlot(64)); + assertEquals(4, s.getContainerCacheSlot(250)); + assertEquals(-1, s.getContainerCacheSlot(1)); + assertEquals(-1, s.getContainerCacheSlot(62)); + assertEquals(-1, s.getContainerCacheSlot(65)); + assertEquals(-1, s.getContainerCacheSlot(299)); + assertThrows(IndexOutOfBoundsException.class, () -> s.getContainerCacheSlot(-1)); + assertThrows(IndexOutOfBoundsException.class, () -> s.getContainerCacheSlot(300)); + } + + // Verify RowWithGetters caches ITERABLE at index 250. + AtomicInteger iterCalls = new AtomicInteger(); + List> getters = new ArrayList<>(300); + for (int i = 0; i < 300; i++) { + final int idx = i; + getters.add( + new FieldValueGetter() { + @Override + public Object get(Object object) { + if (idx == 250) { + iterCalls.incrementAndGet(); + return Arrays.asList("it1", "it2"); + } + return idx; + } + + @Override + public String name() { + return original.getField(idx).getName(); + } + }); + } + Row row = + Row.withFieldValueGetters(original, getters, new Object(), TypeDescriptor.of(Object.class)); + List first = new ArrayList<>(); + Objects.requireNonNull(row.getIterable(250)).forEach(e -> first.add((String) e)); + List second = new ArrayList<>(); + Objects.requireNonNull(row.getIterable(250)).forEach(e -> second.add((String) e)); + assertEquals(Arrays.asList("it1", "it2"), first); + assertEquals(Arrays.asList("it1", "it2"), second); + assertEquals(1, iterCalls.get()); + } +} From cdc5ae1ee0351fa87dd399ca22b7c201ec96b8e0 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:55:38 -0800 Subject: [PATCH 06/15] Optimize Filter, Cast, RenameFields, AddFields, DropFields, and Convert Eliminates unnecessary POJO-to-Row round-trips, per-element schema inspection, and intermediate row copies across core field-level schema transforms: - Filter: operates directly on typed @Element T / OutputReceiver with direct single-field path reads instead of round-tripping POJOs through Row. - Cast: precomputes CastPlan with identity-schema pass-through and zero-copy Row.attachValues output. - RenameFields: precomputes RenamePlan (fixing depth >= 2 rename bugs and avoiding RowWithGetters.getValues() raw-getter hazard). - AddFields / DropFields / Convert: uses direct array access, identity function checks, and Row.attachValues. --- .../sdk/schemas/transforms/AddFields.java | 228 ++++++++--- .../beam/sdk/schemas/transforms/Cast.java | 368 ++++++++++++++++-- .../beam/sdk/schemas/transforms/Convert.java | 89 ++++- .../sdk/schemas/transforms/DropFields.java | 15 +- .../beam/sdk/schemas/transforms/Filter.java | 111 ++++-- .../sdk/schemas/transforms/RenameFields.java | 339 +++++++++------- .../schemas/transforms/RenameFieldsTest.java | 49 ++- 7 files changed, 887 insertions(+), 312 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/AddFields.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/AddFields.java index e04efb3b9c2a..eb57cac32652 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/AddFields.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/AddFields.java @@ -35,11 +35,12 @@ import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Multimap; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Multimaps; @@ -146,6 +147,9 @@ abstract static class AddFieldsInformation implements Serializable { // have new nested values. For other fields, the list contains a null value. abstract List getNestedNewValues(); + // Number of fields from the input schema at this row level (0 for brand-new nested rows). + abstract int getExistingFieldCount(); + @AutoValue.Builder abstract static class Builder { abstract AddFieldsInformation.Builder setOutputFieldType(Schema.FieldType outputFieldType); @@ -155,6 +159,8 @@ abstract static class Builder { abstract AddFieldsInformation.Builder setNestedNewValues( List nestedNewValues); + abstract AddFieldsInformation.Builder setExistingFieldCount(int existingFieldCount); + abstract AddFieldsInformation build(); } @@ -163,11 +169,13 @@ abstract AddFieldsInformation.Builder setNestedNewValues( static AddFieldsInformation of( Schema.FieldType outputFieldType, List defaultValues, - List nestedNewValues) { + List nestedNewValues, + int existingFieldCount) { return new AutoValue_AddFields_Inner_AddFieldsInformation.Builder() .setOutputFieldType(outputFieldType) .setDefaultValues(defaultValues) .setNestedNewValues(nestedNewValues) + .setExistingFieldCount(existingFieldCount) .build(); } } @@ -302,7 +310,10 @@ private static AddFieldsInformation getAddFieldsInformation( nestedNewValueList.set(entry.getKey(), entry.getValue()); } return AddFieldsInformation.of( - Schema.FieldType.row(schema), newValuesThisLevel, nestedNewValueList); + Schema.FieldType.row(schema), + newValuesThisLevel, + nestedNewValueList, + inputSchema.getFieldCount()); } private static AddFieldsInformation getAddFieldsInformation( @@ -343,94 +354,189 @@ private static AddFieldsInformation getAddFieldsInformation( return addFieldsInformation.toBuilder().setOutputFieldType(fieldType).build(); } - private static Row fillNewFields(Row row, AddFieldsInformation addFieldsInformation) { - Schema outputSchema = checkNotNull(addFieldsInformation.getOutputFieldType().getRowSchema()); + /** Precompiled plan for filling added fields without per-row AutoValue copies. */ + private interface ValueFillPlan extends Serializable { + Object fill(@Nullable Object original); + } - List newValues = Lists.newArrayListWithCapacity(outputSchema.getFieldCount()); - for (int i = 0; i < row.getFieldCount(); ++i) { - AddFieldsInformation nested = addFieldsInformation.getNestedNewValues().get(i); - if (nested != null) { - // New fields were added to nested subfields of this value. Recursively fill them out - // before adding to the new row. - Object newValue = fillNewFields(row.getValue(i), nested.getOutputFieldType(), nested); - newValues.add(newValue); + private static final class RowFillPlan implements ValueFillPlan { + final Schema outputSchema; + final int existingFieldCount; + final @Nullable ValueFillPlan @Nullable [] existingNestedPlans; + final @Nullable Object[] appendedTail; + final int totalFieldCount; + + RowFillPlan( + Schema outputSchema, + int existingFieldCount, + @Nullable ValueFillPlan @Nullable [] existingNestedPlans, + @Nullable Object[] appendedTail) { + this.outputSchema = outputSchema; + this.existingFieldCount = existingFieldCount; + this.existingNestedPlans = existingNestedPlans; + this.appendedTail = appendedTail; + this.totalFieldCount = outputSchema.getFieldCount(); + } + + @Override + public Object fill(@Nullable Object original) { + if (original == null) { + @Nullable Object[] out = new Object[totalFieldCount]; + if (appendedTail.length > 0) { + System.arraycopy(appendedTail, 0, out, existingFieldCount, appendedTail.length); + } + return Row.attachValues(outputSchema, out); + } + return fillRow((Row) original); + } + + Row fillRow(Row row) { + @Nullable Object[] out = new Object[totalFieldCount]; + if (existingNestedPlans == null) { + if (row instanceof RowWithStorage) { + @Nullable Object[] raw = ((RowWithStorage) row).getRawArray(); + if (raw != null) { + System.arraycopy(raw, 0, out, 0, existingFieldCount); + } else { + for (int i = 0; i < existingFieldCount; i++) { + out[i] = row.getValue(i); + } + } + } else { + for (int i = 0; i < existingFieldCount; i++) { + out[i] = row.getValue(i); + } + } } else { - // Nothing changed. Just copy the old value into the new row. - newValues.add(row.getValue(i)); + @Nullable Object[] raw = + row instanceof RowWithStorage ? ((RowWithStorage) row).getRawArray() : null; + for (int i = 0; i < existingFieldCount; i++) { + Object val = raw != null ? raw[i] : row.getValue(i); + ValueFillPlan nested = existingNestedPlans[i]; + out[i] = nested != null ? nested.fill(val) : val; + } + } + if (appendedTail.length > 0) { + System.arraycopy(appendedTail, 0, out, existingFieldCount, appendedTail.length); } + return Row.attachValues(outputSchema, out); + } + } + + private static final class CollectionFillPlan implements ValueFillPlan { + final ValueFillPlan elementPlan; + + CollectionFillPlan(ValueFillPlan elementPlan) { + this.elementPlan = elementPlan; } - // If there are brand new simple (i.e. have no nested values) fields at this level, then add - // the default values for all of them. - newValues.addAll(addFieldsInformation.getDefaultValues()); - // If we are creating new recursive fields, populate new values for them here. - for (int i = newValues.size(); i < addFieldsInformation.getNestedNewValues().size(); ++i) { - AddFieldsInformation newNestedField = addFieldsInformation.getNestedNewValues().get(i); - if (newNestedField != null) { - newValues.add(fillNewFields(null, newNestedField.getOutputFieldType(), newNestedField)); + + @Override + @SuppressWarnings("unchecked") + public Object fill(@Nullable Object original) { + if (original == null) { + return Collections.emptyList(); + } + Iterable iterable = (Iterable) original; + List filled = + iterable instanceof Collection + ? new ArrayList<>(((Collection) iterable).size()) + : new ArrayList<>(); + for (Object element : iterable) { + filled.add(elementPlan.fill(element)); } + return filled; } + } - return Row.withSchema(outputSchema).attachValues(newValues); + private static final class MapFillPlan implements ValueFillPlan { + final ValueFillPlan valuePlan; + + MapFillPlan(ValueFillPlan valuePlan) { + this.valuePlan = valuePlan; + } + + @Override + @SuppressWarnings("unchecked") + public Object fill(@Nullable Object original) { + if (original == null) { + return Collections.emptyMap(); + } + Map originalMap = (Map) original; + Map filledMap = Maps.newHashMapWithExpectedSize(originalMap.size()); + for (Map.Entry entry : originalMap.entrySet()) { + filledMap.put(entry.getKey(), valuePlan.fill(entry.getValue())); + } + return filledMap; + } } - private static Object fillNewFields( - Object original, Schema.FieldType fieldType, AddFieldsInformation addFieldsInformation) { + private static ValueFillPlan compileFillPlan( + Schema.FieldType fieldType, AddFieldsInformation info) { switch (fieldType.getTypeName()) { case ROW: - if (original == null) { - original = Row.withSchema(fieldType.getRowSchema()).build(); - } - return fillNewFields((Row) original, addFieldsInformation); - + return compileRowFillPlan(checkNotNull(fieldType.getRowSchema()), info); case ARRAY: case ITERABLE: - if (original == null) { - return Collections.emptyList(); - } - Iterable iterable = (Iterable) original; - List filledList = new ArrayList<>(Iterables.size(iterable)); - Schema.FieldType elementType = fieldType.getCollectionElementType(); - AddFieldsInformation elementAddFieldInformation = - addFieldsInformation.toBuilder().setOutputFieldType(elementType).build(); - for (Object element : iterable) { - filledList.add(fillNewFields(element, elementType, elementAddFieldInformation)); - } - return filledList; - + return new CollectionFillPlan( + compileFillPlan(fieldType.getCollectionElementType(), info)); case MAP: - if (original == null) { - return Collections.emptyMap(); - } - Map originalMap = (Map) original; - Map filledMap = Maps.newHashMapWithExpectedSize(originalMap.size()); - Schema.FieldType mapValueType = fieldType.getMapValueType(); - AddFieldsInformation mapValueAddFieldInformation = - addFieldsInformation.toBuilder().setOutputFieldType(mapValueType).build(); - for (Map.Entry entry : originalMap.entrySet()) { - filledMap.put( - entry.getKey(), - fillNewFields(entry.getValue(), mapValueType, mapValueAddFieldInformation)); - } - return filledMap; - + return new MapFillPlan(compileFillPlan(fieldType.getMapValueType(), info)); default: throw new RuntimeException("Unexpected field type"); } } + private static RowFillPlan compileRowFillPlan(Schema outputSchema, AddFieldsInformation info) { + List nestedList = info.getNestedNewValues(); + List defaultValues = info.getDefaultValues(); + int totalFields = outputSchema.getFieldCount(); + int existingCount = info.getExistingFieldCount(); + int defaultsCount = defaultValues.size(); + + @Nullable ValueFillPlan[] existingPlans = null; + for (int i = 0; i < existingCount; i++) { + AddFieldsInformation nested = nestedList.get(i); + if (nested != null) { + if (existingPlans == null) { + existingPlans = new ValueFillPlan[existingCount]; + } + existingPlans[i] = compileFillPlan(nested.getOutputFieldType(), nested); + } + } + int tailLen = totalFields - existingCount; + @Nullable Object[] tail = new Object[tailLen]; + for (int i = 0; i < defaultsCount; i++) { + tail[i] = defaultValues.get(i); + } + for (int i = existingCount + defaultsCount; i < totalFields; i++) { + AddFieldsInformation newNested = nestedList.get(i); + if (newNested != null) { + tail[i - existingCount] = + compileFillPlan(newNested.getOutputFieldType(), newNested).fill(null); + } + } + return new RowFillPlan(outputSchema, existingCount, existingPlans, tail); + } + @Override public PCollection expand(PCollection input) { final AddFieldsInformation addFieldsInformation = getAddFieldsInformation(input.getSchema(), newFields); Schema outputSchema = checkNotNull(addFieldsInformation.getOutputFieldType().getRowSchema()); + final RowFillPlan fillPlan = compileRowFillPlan(outputSchema, addFieldsInformation); + @Nullable SerializableFunction toRowFn = + org.apache.beam.sdk.schemas.SchemaUtils.isIdentityFunction(input.getToRowFunction()) + ? null + : input.getToRowFunction(); return input .apply( ParDo.of( new DoFn() { @ProcessElement - public void processElement(@Element Row row, OutputReceiver o) { - o.output(fillNewFields(row, addFieldsInformation)); + public void processElement(@Element T element, OutputReceiver o) { + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + o.output(fillPlan.fillRow(row)); } })) .setRowSchema(outputSchema); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Cast.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Cast.java index fa7397d978a9..bd6e2f10d957 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Cast.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Cast.java @@ -21,12 +21,13 @@ import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; -import org.apache.beam.sdk.schemas.FieldAccessDescriptor; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.Field; import org.apache.beam.sdk.schemas.Schema.FieldType; @@ -35,12 +36,16 @@ import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Joiner; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.Cache; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheBuilder; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; +import org.checkerframework.checker.nullness.qual.Nullable; /** Set of utilities for casting rows between schemas. */ @AutoValue @@ -283,52 +288,349 @@ public void verifyCompatibility(Schema inputSchema) { } } + private static final class SchemaPair { + final Schema inputSchema; + final Schema outputSchema; + final int hash; + + SchemaPair(Schema inputSchema, Schema outputSchema) { + this.inputSchema = inputSchema; + this.outputSchema = outputSchema; + int h = inputSchema.hashCode(); + h = 31 * h + outputSchema.hashCode(); + h = 31 * h + Objects.hashCode(outputSchema.getUUID()); + this.hash = h; + } + + @Override + public int hashCode() { + return hash; + } + + @Override + @SuppressWarnings("ReferenceEquality") + public boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } + if (!(o instanceof SchemaPair)) { + return false; + } + SchemaPair that = (SchemaPair) o; + return (inputSchema == that.inputSchema || inputSchema.equals(that.inputSchema)) + && (outputSchema == that.outputSchema || outputSchema.equals(that.outputSchema)) + && Objects.equals(outputSchema.getUUID(), that.outputSchema.getUUID()); + } + } + + private static final Cache CAST_PLAN_CACHE = + CacheBuilder.newBuilder().maximumSize(256).build(); + + private interface ValueCaster { + @Nullable Object cast(@Nullable Object value); + } + + private static final class RowCastPlan { + final Schema outputSchema; + final int[] srcIndices; + final @Nullable ValueCaster[] fieldCasters; + final String @Nullable [] nonNullFieldNames; + final boolean isRewrapOnly; + final boolean isExactIdentity; + final boolean hasNullChecks; + + RowCastPlan( + Schema outputSchema, + int[] srcIndices, + @Nullable ValueCaster[] fieldCasters, + String @Nullable [] nonNullFieldNames, + boolean isRewrapOnly, + boolean isExactIdentity, + boolean hasNullChecks) { + this.outputSchema = outputSchema; + this.srcIndices = srcIndices; + this.fieldCasters = fieldCasters; + this.nonNullFieldNames = nonNullFieldNames; + this.isRewrapOnly = isRewrapOnly; + this.isExactIdentity = isExactIdentity; + this.hasNullChecks = hasNullChecks; + } + + Row cast(Row input) { + if (isExactIdentity) { + return input; + } + int outCount = srcIndices.length; + if (isRewrapOnly) { + if (input instanceof RowWithStorage) { + @Nullable Object[] raw = ((RowWithStorage) input).getRawArray(); + if (raw != null) { + return Row.attachValues(outputSchema, raw); + } + return Row.attachValues(outputSchema, input.getValues()); + } + Object[] out = new Object[outCount]; + for (int i = 0; i < outCount; i++) { + out[i] = input.getValue(i); + } + return Row.attachValues(outputSchema, out); + } + + @Nullable Object[] out = new Object[outCount]; + @Nullable Object[] raw = + input instanceof RowWithStorage ? ((RowWithStorage) input).getRawArray() : null; + for (int i = 0; i < outCount; i++) { + Object v = raw != null ? raw[srcIndices[i]] : input.getValue(srcIndices[i]); + if (v == null) { + if (hasNullChecks && nonNullFieldNames[i] != null) { + throw new IllegalArgumentException( + "Field " + nonNullFieldNames[i] + " is not nullable."); + } + out[i] = null; + } else { + ValueCaster caster = fieldCasters[i]; + out[i] = caster != null ? caster.cast(v) : v; + } + } + return Row.attachValues(outputSchema, out); + } + + static RowCastPlan compile(Schema inputSchema, Schema outputSchema) { + int outCount = outputSchema.getFieldCount(); + int[] srcIndices = new int[outCount]; + @Nullable ValueCaster[] fieldCasters = new ValueCaster[outCount]; + String @Nullable [] nonNullFieldNames = null; + boolean sameOrder = inputSchema.getFieldCount() == outCount; + boolean anyCaster = false; + boolean hasNullChecks = false; + + for (int i = 0; i < outCount; i++) { + Schema.Field outputField = outputSchema.getField(i); + int fromIdx = inputSchema.indexOf(outputField.getName()); + srcIndices[i] = fromIdx; + if (fromIdx != i) { + sameOrder = false; + } + Schema.Field inputField = inputSchema.getField(fromIdx); + FieldType inType = inputField.getType(); + FieldType outType = outputField.getType(); + if (inType.getNullable() && !outType.getNullable()) { + if (nonNullFieldNames == null) { + nonNullFieldNames = new String[outCount]; + } + nonNullFieldNames[i] = outputField.getName(); + hasNullChecks = true; + } + ValueCaster caster = compileValueCaster(inType, outType); + fieldCasters[i] = caster; + if (caster != null) { + anyCaster = true; + } + } + boolean rewrapOnly = sameOrder && !anyCaster && !hasNullChecks; + boolean exactIdentity = + rewrapOnly + && inputSchema.equals(outputSchema) + && Objects.equals(inputSchema.getUUID(), outputSchema.getUUID()); + return new RowCastPlan( + outputSchema, + srcIndices, + fieldCasters, + nonNullFieldNames != null ? nonNullFieldNames : new String[0], + rewrapOnly, + exactIdentity, + hasNullChecks); + } + + @SuppressWarnings("unchecked") + private static @Nullable ValueCaster compileValueCaster(FieldType input, FieldType output) { + TypeName inputType = input.getTypeName(); + TypeName outputType = output.getTypeName(); + switch (inputType) { + case ROW: + RowCastPlan nestedPlan = compile(input.getRowSchema(), output.getRowSchema()); + if (nestedPlan.isExactIdentity) { + return null; + } + return value -> value == null ? null : nestedPlan.cast((Row) value); + case ARRAY: + case ITERABLE: + { + FieldType inElem = input.getCollectionElementType(); + FieldType outElem = output.getCollectionElementType(); + ValueCaster elemCaster = compileValueCaster(inElem, outElem); + boolean checkElemNonNull = inElem.getNullable() && !outElem.getNullable(); + if (elemCaster == null && !checkElemNonNull && inputType == outputType) { + return null; + } + return value -> { + if (value == null) { + return null; + } + Iterable inputValues = (Iterable) value; + List outputValues = + inputValues instanceof Collection + ? new ArrayList<>(((Collection) inputValues).size()) + : new ArrayList<>(); + for (Object elem : inputValues) { + if (elem == null) { + if (checkElemNonNull) { + throw new IllegalArgumentException( + "Cannot cast null element to non-nullable collection element."); + } + outputValues.add(null); + } else { + outputValues.add(elemCaster != null ? elemCaster.cast(elem) : elem); + } + } + return outputValues; + }; + } + case MAP: + { + FieldType inKey = input.getMapKeyType(); + FieldType outKey = output.getMapKeyType(); + FieldType inVal = input.getMapValueType(); + FieldType outVal = output.getMapValueType(); + ValueCaster keyCaster = compileValueCaster(inKey, outKey); + ValueCaster valCaster = compileValueCaster(inVal, outVal); + boolean checkKeyNonNull = inKey.getNullable() && !outKey.getNullable(); + boolean checkValNonNull = inVal.getNullable() && !outVal.getNullable(); + if (keyCaster == null && valCaster == null && !checkKeyNonNull && !checkValNonNull) { + return null; + } + return value -> { + if (value == null) { + return null; + } + Map inputMap = (Map) value; + Map outputMap = Maps.newHashMapWithExpectedSize(inputMap.size()); + for (Map.Entry entry : inputMap.entrySet()) { + Object k = entry.getKey(); + Object v = entry.getValue(); + Object outK; + if (k == null) { + if (checkKeyNonNull) { + throw new IllegalArgumentException( + "Cannot cast null map key to non-nullable key type."); + } + outK = null; + } else { + outK = keyCaster == null ? k : keyCaster.cast(k); + } + Object outV; + if (v == null) { + if (checkValNonNull) { + throw new IllegalArgumentException( + "Cannot cast null map value to non-nullable value type."); + } + outV = null; + } else { + outV = valCaster == null ? v : valCaster.cast(v); + } + outputMap.put(outK, outV); + } + return outputMap; + }; + } + default: + if (inputType == outputType) { + return null; + } + if (inputType.isNumericType() && outputType.isNumericType()) { + return compileNumericCaster(inputType, outputType); + } + return value -> castValue(value, input, output); + } + } + + private static ValueCaster compileNumericCaster(TypeName inputType, TypeName outputType) { + switch (outputType) { + case BYTE: + return v -> v == null ? null : ((Number) v).byteValue(); + case INT16: + return v -> v == null ? null : ((Number) v).shortValue(); + case INT32: + return v -> v == null ? null : ((Number) v).intValue(); + case INT64: + return v -> v == null ? null : ((Number) v).longValue(); + case FLOAT: + return v -> v == null ? null : ((Number) v).floatValue(); + case DOUBLE: + return v -> v == null ? null : ((Number) v).doubleValue(); + case DECIMAL: + switch (inputType) { + case BYTE: + case INT16: + case INT32: + return v -> v == null ? null : BigDecimal.valueOf(((Number) v).intValue()); + case INT64: + return v -> v == null ? null : BigDecimal.valueOf(((Number) v).longValue()); + case FLOAT: + case DOUBLE: + // Preserve exact binary IEEE-754 representation (matches BigDecimal(double)). + return v -> v == null ? null : new BigDecimal(((Number) v).doubleValue()); + default: + throw new AssertionError("Unexpected numeric type: " + outputType); + } + default: + throw new AssertionError("Unexpected numeric type: " + outputType); + } + } + } + + private static RowCastPlan getCastPlan(Schema inputSchema, Schema outputSchema) { + SchemaPair key = new SchemaPair(inputSchema, outputSchema); + RowCastPlan plan = CAST_PLAN_CACHE.getIfPresent(key); + if (plan == null) { + plan = RowCastPlan.compile(inputSchema, outputSchema); + CAST_PLAN_CACHE.put(key, plan); + } + return plan; + } + @Override public PCollection expand(PCollection input) { Schema inputSchema = input.getSchema(); + Schema targetSchema = outputSchema(); verifyCompatibility(inputSchema); + @Nullable SerializableFunction toRowFn = + org.apache.beam.sdk.schemas.SchemaUtils.isIdentityFunction(input.getToRowFunction()) + ? null + : input.getToRowFunction(); + return input .apply( ParDo.of( new DoFn() { - // TODO: This should be the same as resolved so that Beam knows which fields - // are being accessed. Currently Beam only supports wildcard descriptors. - // Once https://github.com/apache/beam/issues/18903 is fixed, fix this. - @FieldAccess("filterFields") - final FieldAccessDescriptor fieldAccessDescriptor = - FieldAccessDescriptor.withAllFields(); + private transient @Nullable RowCastPlan plan; + + @Setup + public void setup() { + this.plan = RowCastPlan.compile(inputSchema, targetSchema); + } @ProcessElement - public void process( - @FieldAccess("filterFields") @Element Row input, OutputReceiver r) { - Row output = castRow(input, inputSchema, outputSchema()); - r.output(output); + public void process(@Element T element, OutputReceiver r) { + RowCastPlan localPlan = this.plan; + if (localPlan == null) { + localPlan = RowCastPlan.compile(inputSchema, targetSchema); + this.plan = localPlan; + } + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + r.output(row == null ? null : localPlan.cast(row)); } })) - .setRowSchema(outputSchema()); + .setRowSchema(targetSchema); } public static Row castRow(Row input, Schema inputSchema, Schema outputSchema) { if (input == null) { return null; } - - Row.Builder output = Row.withSchema(outputSchema); - for (int i = 0; i < outputSchema.getFieldCount(); i++) { - Schema.Field outputField = outputSchema.getField(i); - - int fromFieldIdx = inputSchema.indexOf(outputField.getName()); - Schema.Field inputField = inputSchema.getField(fromFieldIdx); - - Object inputValue = input.getValue(fromFieldIdx); - Object outputValue = castValue(inputValue, inputField.getType(), outputField.getType()); - - output.addValue(outputValue); - } - - return output.build(); + return getCastPlan(inputSchema, outputSchema).cast(input); } public static Number castNumber(Number value, TypeName input, TypeName output) { @@ -372,10 +674,10 @@ public static Number castNumber(Number value, TypeName input, TypeName output) { case BYTE: case INT16: case INT32: - return new BigDecimal(value.intValue()); + return BigDecimal.valueOf(value.intValue()); case INT64: - return new BigDecimal(value.longValue()); + return BigDecimal.valueOf(value.longValue()); case FLOAT: case DOUBLE: @@ -406,9 +708,11 @@ public static Object castValue(Object inputValue, FieldType input, FieldType out case ARRAY: case ITERABLE: - ; Iterable inputValues = (Iterable) inputValue; - List outputValues = new ArrayList<>(Iterables.size(inputValues)); + List outputValues = + inputValues instanceof Collection + ? new ArrayList<>(((Collection) inputValues).size()) + : new ArrayList<>(); for (Object elem : inputValues) { outputValues.add( diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Convert.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Convert.java index c8e5bfecec20..ab8400ddd36a 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Convert.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Convert.java @@ -17,6 +17,7 @@ */ package org.apache.beam.sdk.schemas.transforms; +import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.schemas.SchemaRegistry; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.DefaultTypeConversionsFactory; @@ -28,6 +29,7 @@ import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptor; +import org.checkerframework.checker.nullness.qual.Nullable; /** A set of utilities for converting between different objects supporting schemas. */ @SuppressWarnings({ @@ -118,33 +120,84 @@ public PCollection expand(PCollection input) { ConvertHelpers.getConvertedSchemaInformation( input.getSchema(), outputTypeDescriptor, registry); boolean unbox = converted.unboxedType != null; + @Nullable SerializableFunction toRowFn = + org.apache.beam.sdk.schemas.SchemaUtils.isIdentityFunction(coder.getToRowFunction()) + ? null + : coder.getToRowFunction(); PCollection output; if (converted.outputSchemaCoder != null) { - output = - input.apply( - ParDo.of( - new DoFn() { - @ProcessElement - public void processElement(@Element Row row, OutputReceiver o) { - // Read the row, potentially unboxing if necessary. - Object input = unbox ? row.getValue(0) : row; - // The output has a schema, so we need to convert to the appropriate type. - o.output( - converted.outputSchemaCoder.getFromRowFunction().apply((Row) input)); - } - })); + SerializableFunction fromRowFn = + converted.outputSchemaCoder.getFromRowFunction(); + DoFn doFn; + if (unbox) { + doFn = + new DoFn() { + @ProcessElement + public void processElement(@Element InputT element, OutputReceiver o) { + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + o.output(fromRowFn.apply(row.getRow(0))); + } + }; + } else if (org.apache.beam.sdk.schemas.SchemaUtils.isIdentityFunction(fromRowFn)) { + doFn = + new DoFn() { + @ProcessElement + public void processElement(@Element InputT element, OutputReceiver o) { + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + o.output((OutputT) row); + } + }; + } else { + doFn = + new DoFn() { + @ProcessElement + public void processElement(@Element InputT element, OutputReceiver o) { + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + o.output(fromRowFn.apply(row)); + } + }; + } + output = input.apply(ParDo.of(doFn)); output.setCoder(converted.outputSchemaCoder); } else { - SerializableFunction convertPrimitive = - ConvertHelpers.getConvertPrimitive( - converted.unboxedType, outputTypeDescriptor, new DefaultTypeConversionsFactory()); + FieldType unboxedType = converted.unboxedType; + TypeDescriptor targetType = outputTypeDescriptor; + // Validate conversion eagerly at pipeline construction time without serializing the + // dynamically generated ByteBuddy class. + ConvertHelpers.getConvertPrimitive( + unboxedType, targetType, DefaultTypeConversionsFactory.INSTANCE); output = input.apply( ParDo.of( new DoFn() { + private transient @Nullable SerializableFunction + convertPrimitive; + + @Setup + public void setup() { + this.convertPrimitive = + (SerializableFunction) + ConvertHelpers.getConvertPrimitive( + unboxedType, + targetType, + DefaultTypeConversionsFactory.INSTANCE); + } + @ProcessElement - public void processElement(@Element Row row, OutputReceiver o) { - o.output(convertPrimitive.apply(row.getValue(0))); + public void processElement( + @Element InputT element, OutputReceiver o) { + SerializableFunction fn = this.convertPrimitive; + if (fn == null) { + fn = + (SerializableFunction) + ConvertHelpers.getConvertPrimitive( + unboxedType, + targetType, + DefaultTypeConversionsFactory.INSTANCE); + this.convertPrimitive = fn; + } + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + o.output(fn.apply(row.getValue(0))); } })); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java index c3dc18f1cdd5..f37d8fc7002a 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java @@ -20,9 +20,10 @@ import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists.newArrayList; +import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; +import java.util.Set; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.Field; @@ -89,16 +90,18 @@ FieldAccessDescriptor complement(Schema inputSchema, FieldAccessDescriptor input List fieldNamesToSelect = newArrayList(); Map nestedFieldsToSelect = Maps.newHashMap(); + Set droppedFieldIds = new HashSet<>(input.fieldIdsAccessed()); + Map nestedFields = + Maps.newHashMapWithExpectedSize(input.getNestedFieldsAccessed().size()); + for (FieldAccessDescriptor.FieldDescriptor fd : input.getNestedFieldsAccessed().keySet()) { + nestedFields.put(fd.getFieldId(), fd); + } for (int i = 0; i < inputSchema.getFieldCount(); ++i) { - if (input.fieldIdsAccessed().contains(i)) { + if (droppedFieldIds.contains(i)) { // This field is selected, so exclude it from the complement. continue; } Field field = inputSchema.getField(i); - Map nestedFields = - input.getNestedFieldsAccessed().keySet().stream() - .collect(Collectors.toMap(k -> k.getFieldId(), k -> k)); - FieldAccessDescriptor.FieldDescriptor fieldDescriptor = nestedFields.get(i); if (fieldDescriptor != null) { // Some subfields are selected, so recursively calculate the complementary subfields to diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Filter.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Filter.java index a3db3256b5b8..8e24bd883328 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Filter.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Filter.java @@ -23,6 +23,7 @@ import java.util.stream.Collectors; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.SchemaUtils; import org.apache.beam.sdk.schemas.utils.RowSelector; import org.apache.beam.sdk.schemas.utils.SelectHelpers; import org.apache.beam.sdk.transforms.DoFn; @@ -96,8 +97,6 @@ abstract static class FilterDescription implements Serializable { abstract SerializableFunction getPredicate(); - abstract @Nullable Schema getSelectedSchema(); - abstract boolean getSelectsSingleField(); abstract @Nullable Schema getInputSchema(); @@ -111,24 +110,12 @@ abstract Builder setFieldAccessDescriptor( abstract Builder setPredicate(SerializableFunction predicate); - abstract Builder setSelectedSchema(@Nullable Schema selectedSchema); - abstract Builder setSelectsSingleField(boolean unbox); abstract Builder setInputSchema(@Nullable Schema inputSchema); abstract FilterDescription build(); } - - private transient RowSelector rowSelector; - - public RowSelector getRowSelector() { - if (rowSelector == null) { - rowSelector = - SelectHelpers.getRowSelectorOptimized(getInputSchema(), getFieldAccessDescriptor()); - } - return rowSelector; - } } private final List> filters = Lists.newArrayList(); @@ -184,6 +171,9 @@ public Inner whereFieldIds( @Override public PCollection expand(PCollection input) { Schema inputSchema = input.getSchema(); + if (filters.isEmpty()) { + return input; + } List resolvedFilters = filters.stream() .map( @@ -191,40 +181,95 @@ public PCollection expand(PCollection input) { f.toBuilder() .setFieldAccessDescriptor( f.getFieldAccessDescriptor().resolve(inputSchema)) - .build()) - .map( - f -> - f.toBuilder() .setInputSchema(inputSchema) - .setSelectedSchema( - SelectHelpers.getOutputSchema( - inputSchema, f.getFieldAccessDescriptor())) .build()) .collect(Collectors.toList()); + int count = resolvedFilters.size(); + int[][] directPaths = new int[count][]; + boolean[] selectsSingle = new boolean[count]; + SerializableFunction[] singlePredicates = new SerializableFunction[count]; + SerializableFunction[] rowPredicates = new SerializableFunction[count]; + FieldAccessDescriptor[] selectorDescriptors = new FieldAccessDescriptor[count]; + for (int i = 0; i < count; i++) { + FilterDescription f = resolvedFilters.get(i); + FieldAccessDescriptor resolved = f.getFieldAccessDescriptor(); + selectsSingle[i] = f.getSelectsSingleField(); + if (selectsSingle[i]) { + int[] path = SchemaUtils.tryResolveSingleFieldPath(inputSchema, resolved); + directPaths[i] = path; + singlePredicates[i] = (SerializableFunction) f.getPredicate(); + if (path == null) { + // Validate output schema eagerly at pipeline construction time. + SelectHelpers.getOutputSchema(inputSchema, resolved); + selectorDescriptors[i] = resolved; + } + } else { + SelectHelpers.getOutputSchema(inputSchema, resolved); + rowPredicates[i] = (SerializableFunction) f.getPredicate(); + selectorDescriptors[i] = resolved; + } + } + + @Nullable SerializableFunction toRowFn = + SchemaUtils.isIdentityFunction(input.getToRowFunction()) + ? null + : input.getToRowFunction(); + return input.apply( ParDo.of( new DoFn() { + private transient @Nullable RowSelector[] selectors; + + @Setup + public void setup() { + initSelectors(); + } + + private RowSelector[] initSelectors() { + RowSelector[] local = new RowSelector[count]; + for (int i = 0; i < count; i++) { + if (selectorDescriptors[i] != null) { + local[i] = + SelectHelpers.getRowSelectorOptimized( + inputSchema, selectorDescriptors[i]); + } + } + this.selectors = local; + return local; + } + @ProcessElement - public void process(@Element Row row, OutputReceiver o) { - for (FilterDescription filter : resolvedFilters) { - Row selected = filter.getRowSelector().select(row); - if (filter.getSelectsSingleField()) { - SerializableFunction predicate = - (SerializableFunction) filter.getPredicate(); - if (!predicate.apply(selected.getValue(0))) { + public void process(@Element T element, OutputReceiver o) { + RowSelector[] localSelectors = this.selectors; + if (localSelectors == null) { + localSelectors = initSelectors(); + } + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + for (int i = 0; i < count; i++) { + if (selectsSingle[i]) { + Object value; + int[] path = directPaths[i]; + if (path != null) { + value = + path.length == 1 + ? (row == null ? null : row.getValue(path[0])) + : SchemaUtils.readFieldPath(row, path); + } else { + value = localSelectors[i].select(row).getValue(0); + } + if (!singlePredicates[i].apply(value)) { return; } } else { - SerializableFunction predicate = - (SerializableFunction) filter.getPredicate(); - if (!predicate.apply(selected)) { + Row selected = localSelectors[i].select(row); + if (!rowPredicates[i].apply(selected)) { return; } } } - // All filters passed. Output the row. - o.output(row); + // All filters passed. Output the original element directly. + o.output(element); } })); } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/RenameFields.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/RenameFields.java index f67695317733..65e94202643d 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/RenameFields.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/RenameFields.java @@ -19,23 +19,24 @@ import com.google.auto.value.AutoValue; import java.io.Serializable; -import java.util.BitSet; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.UUID; import java.util.stream.Collectors; -import javax.annotation.Nullable; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.Field; import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.SchemaUtils; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ArrayListMultimap; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; @@ -43,6 +44,7 @@ import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Multimap; +import org.checkerframework.checker.nullness.qual.Nullable; /** * A transform for renaming fields inside an existing schema. Top level or nested fields can be @@ -90,88 +92,204 @@ RenamePair resolve(Schema schema) { } } - private static FieldType renameFieldType( - FieldType inputType, - Collection renames, - Map renamedSchemasMap, - Map nestedFieldRenamedMap) { - if (renames.isEmpty()) { - return inputType; + /** Precompiled per-field rename plan enabling fast, UUID-free multi-level renaming. */ + private interface FieldRenamePlan extends Serializable { + @Nullable Object apply(@Nullable Object value); + } + + @VisibleForTesting + static final class RowRenamePlan implements FieldRenamePlan { + final Schema outputSchema; + final @Nullable FieldRenamePlan @Nullable [] fieldPlans; + + RowRenamePlan(Schema outputSchema, @Nullable FieldRenamePlan @Nullable [] fieldPlans) { + this.outputSchema = outputSchema; + this.fieldPlans = fieldPlans; } - switch (inputType.getTypeName()) { - case ROW: - renameSchema(inputType.getRowSchema(), renames, renamedSchemasMap, nestedFieldRenamedMap); - return FieldType.row(renamedSchemasMap.get(inputType.getRowSchema().getUUID())); - case ARRAY: - return FieldType.array( - renameFieldType( - inputType.getCollectionElementType(), - renames, - renamedSchemasMap, - nestedFieldRenamedMap)); - case ITERABLE: - return FieldType.iterable( - renameFieldType( - inputType.getCollectionElementType(), - renames, - renamedSchemasMap, - nestedFieldRenamedMap)); - case MAP: - return FieldType.map( - renameFieldType( - inputType.getMapKeyType(), renames, renamedSchemasMap, nestedFieldRenamedMap), - renameFieldType( - inputType.getMapValueType(), renames, renamedSchemasMap, nestedFieldRenamedMap)); - case LOGICAL_TYPE: - throw new RuntimeException("RenameFields does not support renaming logical types."); - default: - return inputType; + @Override + public @Nullable Object apply(@Nullable Object value) { + return value == null ? null : rename((Row) value); + } + + Row rename(Row row) { + if (row == null) { + return null; + } + if (fieldPlans == null) { + if (row instanceof RowWithStorage) { + @Nullable Object[] raw = ((RowWithStorage) row).getRawArray(); + if (raw != null) { + return Row.attachValues(outputSchema, raw); + } + return Row.attachValues(outputSchema, row.getValues()); + } + int n = outputSchema.getFieldCount(); + Object[] values = new Object[n]; + for (int i = 0; i < n; i++) { + values[i] = row.getValue(i); + } + return Row.attachValues(outputSchema, values); + } + int n = outputSchema.getFieldCount(); + Object[] values = new Object[n]; + @Nullable Object[] raw = + row instanceof RowWithStorage ? ((RowWithStorage) row).getRawArray() : null; + for (int i = 0; i < n; i++) { + Object val = raw != null ? raw[i] : row.getValue(i); + FieldRenamePlan childPlan = fieldPlans[i]; + values[i] = (childPlan != null && val != null) ? childPlan.apply(val) : val; + } + return Row.attachValues(outputSchema, values); + } + } + + private static final class CollectionRenamePlan implements FieldRenamePlan { + final FieldRenamePlan elementPlan; + + CollectionRenamePlan(FieldRenamePlan elementPlan) { + this.elementPlan = elementPlan; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable Object apply(@Nullable Object value) { + if (value == null) { + return null; + } + Iterable iterable = (Iterable) value; + List renamed = + iterable instanceof Collection + ? new ArrayList<>(((Collection) iterable).size()) + : new ArrayList<>(); + for (Object elem : iterable) { + renamed.add(elem == null ? null : elementPlan.apply(elem)); + } + return renamed; + } + } + + private static final class MapRenamePlan implements FieldRenamePlan { + final @Nullable FieldRenamePlan keyPlan; + final @Nullable FieldRenamePlan valuePlan; + + MapRenamePlan(@Nullable FieldRenamePlan keyPlan, @Nullable FieldRenamePlan valuePlan) { + this.keyPlan = keyPlan; + this.valuePlan = valuePlan; + } + + @Override + @SuppressWarnings("unchecked") + public @Nullable Object apply(@Nullable Object value) { + if (value == null) { + return null; + } + Map inputMap = (Map) value; + Map out = Maps.newHashMapWithExpectedSize(inputMap.size()); + for (Map.Entry entry : inputMap.entrySet()) { + Object k = entry.getKey(); + Object v = entry.getValue(); + Object outK = (keyPlan != null && k != null) ? keyPlan.apply(k) : k; + Object outV = (valuePlan != null && v != null) ? valuePlan.apply(v) : v; + out.put(outK, outV); + } + return out; + } + } + + private static final class FieldPlanResult { + final FieldType fieldType; + final @Nullable FieldRenamePlan plan; + + FieldPlanResult(FieldType fieldType, @Nullable FieldRenamePlan plan) { + this.fieldType = fieldType; + this.plan = plan; } } - // Apply the user-specified renames to the input schema. @VisibleForTesting - static void renameSchema( - Schema inputSchema, - Collection renames, - Map renamedSchemasMap, - Map nestedFieldRenamedMap) { - // The mapping of renames to apply at this level of the schema. + static RowRenamePlan buildRenamePlan(Schema inputSchema, Collection renames) { Map topLevelRenames = Maps.newHashMap(); - // For nested schemas, collect all applicable renames here. Multimap nestedRenames = ArrayListMultimap.create(); for (RenamePair rename : renames) { FieldAccessDescriptor access = rename.getFieldAccessDescriptor(); if (!access.fieldIdsAccessed().isEmpty()) { - // This references a field at this level of the schema. Integer fieldId = Iterables.getOnlyElement(access.fieldIdsAccessed()); topLevelRenames.put(fieldId, rename.getNewName()); } else { - // This references a nested field. Map.Entry nestedAccess = Iterables.getOnlyElement(access.nestedFieldsById().entrySet()); - nestedFieldRenamedMap - .computeIfAbsent(inputSchema.getUUID(), s -> new BitSet(inputSchema.getFieldCount())) - .set(nestedAccess.getKey()); nestedRenames.put( nestedAccess.getKey(), RenamePair.of(nestedAccess.getValue(), rename.getNewName())); } } + int fieldCount = inputSchema.getFieldCount(); + @Nullable FieldRenamePlan[] childPlans = null; Schema.Builder builder = Schema.builder(); - for (int i = 0; i < inputSchema.getFieldCount(); ++i) { + for (int i = 0; i < fieldCount; i++) { Field field = inputSchema.getField(i); - FieldType fieldType = field.getType(); String newName = topLevelRenames.getOrDefault(i, field.getName()); - Collection nestedFieldRenames = + Collection nested = nestedRenames.asMap().getOrDefault(i, Collections.emptyList()); - builder.addField( - newName, - renameFieldType(fieldType, nestedFieldRenames, renamedSchemasMap, nestedFieldRenamedMap)); + if (nested.isEmpty()) { + builder.addField(field.withName(newName)); + } else { + FieldPlanResult res = buildFieldPlan(field.getType(), nested); + builder.addField(field.withName(newName).withType(res.fieldType)); + if (res.plan != null) { + if (childPlans == null) { + childPlans = new FieldRenamePlan[fieldCount]; + } + childPlans[i] = res.plan; + } + } + } + return new RowRenamePlan(builder.build(), childPlans); + } + + private static FieldPlanResult buildFieldPlan( + FieldType inputType, Collection renames) { + if (renames.isEmpty()) { + return new FieldPlanResult(inputType, null); + } + switch (inputType.getTypeName()) { + case ROW: + RowRenamePlan child = buildRenamePlan(inputType.getRowSchema(), renames); + return new FieldPlanResult( + FieldType.row(child.outputSchema) + .withNullable(inputType.getNullable()) + .withMetadata(inputType.getAllMetadata()), + child); + case ARRAY: + FieldPlanResult arrElem = buildFieldPlan(inputType.getCollectionElementType(), renames); + return new FieldPlanResult( + FieldType.array(arrElem.fieldType) + .withNullable(inputType.getNullable()) + .withMetadata(inputType.getAllMetadata()), + arrElem.plan == null ? null : new CollectionRenamePlan(arrElem.plan)); + case ITERABLE: + FieldPlanResult iterElem = buildFieldPlan(inputType.getCollectionElementType(), renames); + return new FieldPlanResult( + FieldType.iterable(iterElem.fieldType) + .withNullable(inputType.getNullable()) + .withMetadata(inputType.getAllMetadata()), + iterElem.plan == null ? null : new CollectionRenamePlan(iterElem.plan)); + case MAP: + // FieldAccessDescriptor.resolve resolves nested map renames against the map value schema + // only; do not apply value-resolved field IDs to composite map keys. + FieldPlanResult valRes = buildFieldPlan(inputType.getMapValueType(), renames); + return new FieldPlanResult( + FieldType.map(inputType.getMapKeyType(), valRes.fieldType) + .withNullable(inputType.getNullable()) + .withMetadata(inputType.getAllMetadata()), + valRes.plan == null ? null : new MapRenamePlan(null, valRes.plan)); + case LOGICAL_TYPE: + throw new RuntimeException("RenameFields does not support renaming logical types."); + default: + return new FieldPlanResult(inputType, null); } - renamedSchemasMap.put(inputSchema.getUUID(), builder.build()); } /** The class implementing the actual PTransform. */ @@ -204,104 +322,31 @@ public Inner rename(FieldAccessDescriptor field, String newName) { @Override public PCollection expand(PCollection input) { - final Map renamedSchemasMap = Maps.newHashMap(); - final Map nestedFieldRenamedMap = Maps.newHashMap(); - + Schema inputSchema = input.getSchema(); + @Nullable SerializableFunction toRowFn = + SchemaUtils.isIdentityFunction(input.getToRowFunction()) + ? null + : input.getToRowFunction(); + if (renames.isEmpty() && toRowFn == null) { + @SuppressWarnings("unchecked") + PCollection passthrough = (PCollection) input; + return passthrough; + } List resolvedRenames = - renames.stream().map(r -> r.resolve(input.getSchema())).collect(Collectors.toList()); - renameSchema(input.getSchema(), resolvedRenames, renamedSchemasMap, nestedFieldRenamedMap); - final Schema outputSchema = renamedSchemasMap.get(input.getSchema().getUUID()); - final BitSet nestedRenames = nestedFieldRenamedMap.get(input.getSchema().getUUID()); + renames.stream().map(r -> r.resolve(inputSchema)).collect(Collectors.toList()); + final RowRenamePlan plan = buildRenamePlan(inputSchema, resolvedRenames); + final Schema outputSchema = plan.outputSchema; return input .apply( ParDo.of( new DoFn() { @ProcessElement - public void processElement(@Element Row row, OutputReceiver o) { - o.output( - renameRow( - row, - outputSchema, - nestedRenames, - renamedSchemasMap, - nestedFieldRenamedMap)); + public void processElement(@Element T element, OutputReceiver o) { + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + o.output(plan.rename(row)); } })) .setRowSchema(outputSchema); } } - - // TODO(reuvenlax): For better performance, we should reuse functionality in - // SelectByteBuddyHelpers to generate - // byte code to do the rename. This would allow us to skip walking over the schema on each row. - // For now we added - // the optimization to skip schema walking if there are no nested renames (as determined by the - // nestedFieldRenamedMap). - @VisibleForTesting - static Row renameRow( - Row row, - Schema schema, - @Nullable BitSet nestedRenames, - Map renamedSubSchemasMap, - Map nestedFieldRenamedMap) { - if (nestedRenames == null || nestedRenames.isEmpty()) { - // Fast path, short circuit subschems. - return Row.withSchema(schema).attachValues(row.getValues()); - } else { - List values = Lists.newArrayListWithCapacity(row.getValues().size()); - for (int i = 0; i < schema.getFieldCount(); ++i) { - if (nestedRenames.get(i)) { - values.add( - renameFieldValue( - row.getValue(i), - schema.getField(i).getType(), - renamedSubSchemasMap, - nestedFieldRenamedMap)); - } else { - values.add(row.getValue(i)); - } - } - return Row.withSchema(schema).attachValues(values); - } - } - - private static Object renameFieldValue( - Object value, - FieldType fieldType, - Map renamedSubSchemas, - Map nestedFieldRenamed) { - switch (fieldType.getTypeName()) { - case ARRAY: - case ITERABLE: - List renamedValues = Lists.newArrayList(); - for (Object o : (List) value) { - renamedValues.add( - renameFieldValue( - o, fieldType.getCollectionElementType(), renamedSubSchemas, nestedFieldRenamed)); - } - return renamedValues; - case MAP: - Map renamedMap = Maps.newHashMap(); - for (Map.Entry entry : ((Map) value).entrySet()) { - renamedMap.put( - renameFieldValue( - entry.getKey(), fieldType.getMapKeyType(), renamedSubSchemas, nestedFieldRenamed), - renameFieldValue( - entry.getValue(), - fieldType.getMapValueType(), - renamedSubSchemas, - nestedFieldRenamed)); - } - return renamedMap; - case ROW: - return renameRow( - (Row) value, - fieldType.getRowSchema(), - nestedFieldRenamed.get(fieldType.getRowSchema().getUUID()), - renamedSubSchemas, - nestedFieldRenamed); - default: - return value; - } - } } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/RenameFieldsTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/RenameFieldsTest.java index 897792e94921..35d1e08d1098 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/RenameFieldsTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/RenameFieldsTest.java @@ -19,10 +19,7 @@ import static junit.framework.TestCase.assertEquals; -import java.util.BitSet; import java.util.List; -import java.util.Map; -import java.util.UUID; import java.util.stream.Collectors; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; import org.apache.beam.sdk.schemas.Schema; @@ -35,7 +32,6 @@ import org.apache.beam.sdk.values.Row; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -290,11 +286,9 @@ public void testRenameRow() { .map(r -> r.resolve(schema)) .collect(Collectors.toList()); - final Map renamedSchemasMap = Maps.newHashMap(); - final Map nestedFieldRenamedMap = Maps.newHashMap(); - RenameFields.renameSchema(schema, renames, renamedSchemasMap, nestedFieldRenamedMap); + RenameFields.RowRenamePlan plan = RenameFields.buildRenamePlan(schema, renames); - assertEquals(expectedSchema, renamedSchemasMap.get(schema.getUUID())); + assertEquals(expectedSchema, plan.outputSchema); Row row = Row.withSchema(schema) @@ -317,13 +311,38 @@ public void testRenameRow() { .build()) .build(); - Row renamedRow = - RenameFields.renameRow( - row, - renamedSchemasMap.get(schema.getUUID()), - nestedFieldRenamedMap.get(schema.getUUID()), - renamedSchemasMap, - nestedFieldRenamedMap); + Row renamedRow = plan.rename(row); assertEquals(expectedRow, renamedRow); } + + @Test + public void testRenameMapWithCompositeRowKeyDoesNotAlterKey() { + Schema keySchema = Schema.builder().addStringField("k").addInt32Field("idx").build(); + Schema valSchema = Schema.builder().addStringField("v1").addInt32Field("v2").build(); + Schema schema = + Schema.builder() + .addMapField("m", Schema.FieldType.row(keySchema), Schema.FieldType.row(valSchema)) + .build(); + List renames = + ImmutableList.of(RenamePair.of(FieldAccessDescriptor.withFieldNames("m.v1"), "renamed_v1")) + .stream() + .map(r -> r.resolve(schema)) + .collect(Collectors.toList()); + + RenameFields.RowRenamePlan plan = RenameFields.buildRenamePlan(schema, renames); + assertEquals( + keySchema, plan.outputSchema.getField("m").getType().getMapKeyType().getRowSchema()); + Schema expectedValSchema = + Schema.builder().addStringField("renamed_v1").addInt32Field("v2").build(); + assertEquals( + expectedValSchema, + plan.outputSchema.getField("m").getType().getMapValueType().getRowSchema()); + + Row keyRow = Row.withSchema(keySchema).addValues("a", 1).build(); + Row valRow = Row.withSchema(valSchema).addValues("hello", 2).build(); + Row inputRow = Row.withSchema(schema).addValue(ImmutableMap.of(keyRow, valRow)).build(); + Row renamed = plan.rename(inputRow); + Row expectedValRow = Row.withSchema(expectedValSchema).addValues("hello", 2).build(); + assertEquals(ImmutableMap.of(keyRow, expectedValRow), renamed.getMap("m")); + } } From 44caece71c0a54053159a3a186b819f67967799d Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:55:59 -0800 Subject: [PATCH 07/15] Optimize Select, SelectByteBuddyHelpers, SelectHelpers, and WithKeys Eliminates eager full-row cloning on wildcard field access and bounds selector codegen caching: - SelectByteBuddyHelpers: short-circuits wildcard getAllFields() to return input directly, parameterizes outputSchema (fixing uniquifyNames leaks and UUID mismatches), hoists checkcasts, optimizes list/map selection, and bounds the generated selector cache at 512 entries. - SelectHelpers / Select / WithKeys: adds output-schema-aware RowSelectorContainer constructor, caches RowSelector transiently on DoFns, and shares rewrapRow/countRowFields helpers. --- .../beam/sdk/schemas/transforms/Select.java | 76 +- .../beam/sdk/schemas/transforms/WithKeys.java | 29 +- .../schemas/utils/SelectByteBuddyHelpers.java | 1070 +++++++++++------ .../beam/sdk/schemas/utils/SelectHelpers.java | 306 +++-- 4 files changed, 938 insertions(+), 543 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Select.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Select.java index 53a9bb14ce65..1485f96bf3bb 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Select.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Select.java @@ -24,7 +24,6 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.UUID; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.Field; @@ -126,22 +125,34 @@ public static Flattened flattenedSchema() { } private static class SelectDoFn extends DoFn { - RowSelector rowSelector; - - // TODO: This should be the same as resolved so that Beam knows which fields - // are being accessed. Currently Beam only supports wildcard descriptors. - // Once https://github.com/apache/beam/issues/18903 is fixed, fix this. - @SuppressWarnings("unused") - @FieldAccess("selectFields") - final FieldAccessDescriptor fieldAccess = FieldAccessDescriptor.withAllFields(); + private final RowSelectorContainer rowSelectorContainer; + private final @Nullable SerializableFunction toRowFunction; + private transient @Nullable RowSelector rowSelector; + + public SelectDoFn( + FieldAccessDescriptor fieldAccessDescriptor, + Schema inputSchema, + Schema outputSchema, + @Nullable SerializableFunction toRowFunction) { + this.rowSelectorContainer = + new RowSelectorContainer(inputSchema, fieldAccessDescriptor, outputSchema, true); + this.toRowFunction = toRowFunction; + } - public SelectDoFn(FieldAccessDescriptor fieldAccessDescriptor, Schema inputSchema) { - this.rowSelector = new RowSelectorContainer(inputSchema, fieldAccessDescriptor, true); + @Setup + public void setup() { + this.rowSelector = rowSelectorContainer.getOrCreateSelector(); } @ProcessElement - public void process(@FieldAccess("selectFields") @Element Row row, OutputReceiver r) { - r.output(rowSelector.select(row)); + public void process(@Element T element, OutputReceiver r) { + RowSelector selector = this.rowSelector; + if (selector == null) { + selector = rowSelectorContainer.getOrCreateSelector(); + this.rowSelector = selector; + } + Row row = toRowFunction != null ? toRowFunction.apply(element) : (Row) element; + r.output(selector.select(row)); } } @@ -191,8 +202,7 @@ public PCollection expand(PCollection input) { if (outputSchema == null) { outputSchema = SelectHelpers.getOutputSchema(inputSchema, resolved); } else { - inputSchema = uniquifyNames(inputSchema); - Schema inferredSchema = SelectHelpers.getOutputSchema(inputSchema, resolved); + Schema inferredSchema = SelectHelpers.getOutputSchema(uniquifyNames(inputSchema), resolved); Preconditions.checkArgument( outputSchema.typesEqual(inferredSchema), "Types not equal. provided output schema: " @@ -202,36 +212,49 @@ public PCollection expand(PCollection input) { + " from input type: " + input.getSchema()); } + @Nullable SerializableFunction toRowFn = + org.apache.beam.sdk.schemas.SchemaUtils.isIdentityFunction(input.getToRowFunction()) + ? null + : input.getToRowFunction(); + if (resolved.getAllFields() && outputSchema.equals(inputSchema) && toRowFn == null) { + @SuppressWarnings("unchecked") + PCollection passthrough = (PCollection) input; + return passthrough; + } return input - .apply(ParDo.of(new SelectDoFn<>(resolved, inputSchema))) + .apply(ParDo.of(new SelectDoFn<>(resolved, inputSchema, outputSchema, toRowFn))) .setRowSchema(outputSchema); } } private static Schema uniquifyNames(Schema schema) { + return uniquifyNames(schema, new int[] {0}); + } + + private static Schema uniquifyNames(Schema schema, int[] counter) { Schema.Builder builder = new Schema.Builder(); for (Field field : schema.getFields()) { - builder.addField(UUID.randomUUID().toString(), uniquifyNames(field.getType())); + builder.addField("_f" + counter[0]++, uniquifyNames(field.getType(), counter)); } return builder.build(); } - private static FieldType uniquifyNames(FieldType fieldType) { + private static FieldType uniquifyNames(FieldType fieldType, int[] counter) { switch (fieldType.getTypeName()) { case ROW: - return FieldType.row(uniquifyNames(fieldType.getRowSchema())) + return FieldType.row(uniquifyNames(fieldType.getRowSchema(), counter)) .withNullable(fieldType.getNullable()) .withMetadata(fieldType.getAllMetadata()); case ARRAY: - return FieldType.array(uniquifyNames(fieldType.getCollectionElementType())) + return FieldType.array(uniquifyNames(fieldType.getCollectionElementType(), counter)) .withNullable(fieldType.getNullable()); case ITERABLE: - return FieldType.iterable(uniquifyNames(fieldType.getCollectionElementType())) + return FieldType.iterable(uniquifyNames(fieldType.getCollectionElementType(), counter)) .withNullable(fieldType.getNullable()); case MAP: return FieldType.map( - uniquifyNames(fieldType.getMapKeyType()), - uniquifyNames(fieldType.getMapValueType())) + uniquifyNames(fieldType.getMapKeyType(), counter), + uniquifyNames(fieldType.getMapValueType(), counter)) .withNullable(fieldType.getNullable()); default: return fieldType; @@ -315,8 +338,13 @@ public PCollection expand(PCollection input) { } else { outputSchema = inferredOutputSchema; } + @Nullable SerializableFunction toRowFn = + org.apache.beam.sdk.schemas.SchemaUtils.isIdentityFunction(input.getToRowFunction()) + ? null + : input.getToRowFunction(); return input - .apply(ParDo.of(new SelectDoFn<>(fieldAccessDescriptor, inputSchema))) + .apply( + ParDo.of(new SelectDoFn<>(fieldAccessDescriptor, inputSchema, outputSchema, toRowFn))) .setRowSchema(outputSchema); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/WithKeys.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/WithKeys.java index d057b75c6779..607290b3ccd1 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/WithKeys.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/WithKeys.java @@ -32,6 +32,7 @@ import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptor; +import org.checkerframework.checker.nullness.qual.Nullable; public class WithKeys extends PTransform, PCollection>> { private final FieldAccessDescriptor fieldAccessDescriptor; @@ -53,22 +54,38 @@ public PCollection> expand(PCollection input) { } SerializableFunction toRowFunction = input.getToRowFunction(); SerializableFunction fromRowFunction = input.getFromRowFunction(); + @Nullable SerializableFunction directToRow = + org.apache.beam.sdk.schemas.SchemaUtils.isIdentityFunction(toRowFunction) + ? null + : toRowFunction; FieldAccessDescriptor resolved = fieldAccessDescriptor.resolve(schema); - RowSelector rowSelector = new RowSelectorContainer(schema, resolved, true); Schema keySchema = SelectHelpers.getOutputSchema(schema, resolved); + RowSelectorContainer selectorContainer = + new RowSelectorContainer(schema, resolved, keySchema, true); return input .apply( "selectKeys", ParDo.of( new DoFn>() { + private transient @Nullable RowSelector rowSelector; + + @Setup + public void setup() { + this.rowSelector = selectorContainer.getOrCreateSelector(); + } + @ProcessElement - public void process( - @Element Row row, // Beam will convert the element to a row. - @Element T element, // Beam will return the original element. - OutputReceiver> o) { - o.output(KV.of(rowSelector.select(row), element)); + @SuppressWarnings({"unchecked", "nullness"}) + public void process(@Element T element, OutputReceiver> o) { + RowSelector selector = this.rowSelector; + if (selector == null) { + selector = selectorContainer.getOrCreateSelector(); + this.rowSelector = selector; + } + Row row = directToRow != null ? directToRow.apply(element) : (Row) element; + o.output(KV.of(selector.select(row), element)); } })) .setCoder( diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectByteBuddyHelpers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectByteBuddyHelpers.java index 32a418dcbb9a..3a879716e9c5 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectByteBuddyHelpers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectByteBuddyHelpers.java @@ -21,14 +21,18 @@ import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; import com.google.auto.value.AutoValue; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.IntStream; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import net.bytebuddy.ByteBuddy; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.method.MethodDescription; @@ -41,7 +45,6 @@ import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.Implementation.Context; import net.bytebuddy.implementation.bytecode.ByteCodeAppender; -import net.bytebuddy.implementation.bytecode.ByteCodeAppender.Size; import net.bytebuddy.implementation.bytecode.Duplication; import net.bytebuddy.implementation.bytecode.Removal; import net.bytebuddy.implementation.bytecode.StackManipulation; @@ -49,7 +52,6 @@ import net.bytebuddy.implementation.bytecode.assign.TypeCasting; import net.bytebuddy.implementation.bytecode.collection.ArrayAccess; import net.bytebuddy.implementation.bytecode.constant.IntegerConstant; -import net.bytebuddy.implementation.bytecode.constant.NullConstant; import net.bytebuddy.implementation.bytecode.member.FieldAccess; import net.bytebuddy.implementation.bytecode.member.MethodInvocation; import net.bytebuddy.implementation.bytecode.member.MethodReturn; @@ -64,57 +66,79 @@ import org.apache.beam.sdk.schemas.FieldAccessDescriptor.FieldDescriptor.Qualifier; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.FieldType; -import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.IfNullElse; -import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ShortCircuitReturnNull; import org.apache.beam.sdk.util.common.ReflectHelpers; import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; +import org.checkerframework.checker.nullness.qual.Nullable; @SuppressWarnings({ - "nullness" // TODO(https://github.com/apache/beam/issues/20497) + "nullness", // TODO(https://github.com/apache/beam/issues/20497) + "ReferenceEquality" }) class SelectByteBuddyHelpers { private static final ByteBuddy BYTE_BUDDY = new ByteBuddy(); private static final String SELECT_SCHEMA_FIELD_NAME = "OUTPUTSCHEMA"; + /** + * Maximum estimated bytecode size (bytes) of a generated {@code select()} method before falling + * back to loop-based selection to stay well below HotSpot C2's default 8KB {@code + * HugeMethodLimit} and JVM 64KB bytecode limit. + */ + private static final int MAX_ESTIMATED_BYTECODE_BYTES = 6000; + + private static final int MAX_GENERATED_SELECTOR_CLASSES = 512; + private static final ForLoadedType ROW_LOADED_TYPE = new ForLoadedType(Row.class); - private static final ForLoadedType LIST_LOADED_TYPE = new ForLoadedType(List.class); - private static final ForLoadedType LISTS_LOADED_TYPE = new ForLoadedType(Lists.class); + private static final ForLoadedType ROW_WITH_STORAGE_TYPE = + new ForLoadedType(RowWithStorage.class); + private static final ForLoadedType ARRAY_LIST_TYPE = new ForLoadedType(ArrayList.class); + private static final ForLoadedType HASH_MAP_TYPE = new ForLoadedType(HashMap.class); private static final ForLoadedType MAP_LOADED_TYPE = new ForLoadedType(Map.class); - private static final ForLoadedType MAPS_LOADED_TYPE = new ForLoadedType(Maps.class); private static final ForLoadedType MAPENTRY_LOADED_TYPE = new ForLoadedType(Map.Entry.class); private static final ForLoadedType ITERABLE_LOADED_TYPE = new ForLoadedType(Iterable.class); private static final ForLoadedType ITERATOR_LOADED_TYPE = new ForLoadedType(Iterator.class); + private static final ForLoadedType SELF_LOADED_TYPE = + new ForLoadedType(SelectByteBuddyHelpers.class); - private static final MethodDescription LIST_ADD = - LIST_LOADED_TYPE + private static final MethodDescription ROW_GET_VALUE = + ROW_LOADED_TYPE .getDeclaredMethods() - .filter(ElementMatchers.named("add").and(ElementMatchers.takesArguments(1))) + .filter(ElementMatchers.named("getValue").and(ElementMatchers.takesArguments(int.class))) .getOnly(); - private static final MethodDescription LISTS_NEW_ARRAYLIST = - LISTS_LOADED_TYPE + private static final MethodDescription ROW_ATTACH_VALUES = + ROW_LOADED_TYPE .getDeclaredMethods() - .filter(ElementMatchers.named("newArrayList").and(ElementMatchers.takesArguments(0))) + .filter( + ElementMatchers.named("attachValues") + .and(ElementMatchers.takesArguments(Schema.class, Object[].class))) .getOnly(); - private static final MethodDescription MAP_ENTRYSET = - MAP_LOADED_TYPE.getDeclaredMethods().filter(ElementMatchers.named("entrySet")).getOnly(); + private static final MethodDescription ROW_WITH_STORAGE_RAW_ARRAY = + ROW_WITH_STORAGE_TYPE + .getDeclaredMethods() + .filter(ElementMatchers.named("getRawArray").and(ElementMatchers.takesArguments(0))) + .getOnly(); - private static final MethodDescription MAP_PUT = - MAP_LOADED_TYPE + private static final MethodDescription ARRAY_LIST_ADD = + ARRAY_LIST_TYPE .getDeclaredMethods() - .filter(ElementMatchers.named("put").and(ElementMatchers.takesArguments(2))) + .filter(ElementMatchers.named("add").and(ElementMatchers.takesArguments(Object.class))) .getOnly(); - private static final MethodDescription MAPS_NEW_HASHMAP = - MAPS_LOADED_TYPE + private static final MethodDescription HASH_MAP_PUT = + HASH_MAP_TYPE .getDeclaredMethods() - .filter(ElementMatchers.named("newHashMap").and(ElementMatchers.takesArguments(0))) + .filter( + ElementMatchers.named("put") + .and(ElementMatchers.takesArguments(Object.class, Object.class))) .getOnly(); + private static final MethodDescription MAP_ENTRYSET = + MAP_LOADED_TYPE.getDeclaredMethods().filter(ElementMatchers.named("entrySet")).getOnly(); + private static final MethodDescription ITERABLE_ITERATOR = ITERABLE_LOADED_TYPE.getDeclaredMethods().filter(ElementMatchers.named("iterator")).getOnly(); @@ -130,6 +154,38 @@ class SelectByteBuddyHelpers { private static final MethodDescription MAPENTRY_GETVALUE = MAPENTRY_LOADED_TYPE.getDeclaredMethods().filter(ElementMatchers.named("getValue")).getOnly(); + private static final MethodDescription NEW_LIST_FOR_ITERABLE = + SELF_LOADED_TYPE + .getDeclaredMethods() + .filter(ElementMatchers.named("newListForIterable")) + .getOnly(); + + private static final MethodDescription NEW_MAP_FOR_MAP = + SELF_LOADED_TYPE + .getDeclaredMethods() + .filter(ElementMatchers.named("newHashMapForMap")) + .getOnly(); + + private static final MethodDescription CLEAR_RANGE = + SELF_LOADED_TYPE.getDeclaredMethods().filter(ElementMatchers.named("clearRange")).getOnly(); + + /** Bytecode helper: allocates an {@link ArrayList} pre-sized to match the input iterable. */ + public static ArrayList newListForIterable(Iterable iterable) { + return iterable instanceof Collection + ? new ArrayList<>(((Collection) iterable).size()) + : new ArrayList<>(); + } + + /** Bytecode helper: allocates a {@link HashMap} pre-sized to match the input map. */ + public static HashMap newHashMapForMap(Map map) { + return Maps.newHashMapWithExpectedSize(map.size()); + } + + /** Bytecode helper: clears a slice of a reused scratch array when a sub-row/container is null. */ + public static void clearRange(Object[] array, int fromIndex, int toIndex) { + Arrays.fill(array, fromIndex, toIndex, null); + } + @AutoValue abstract static class SchemaAndDescriptor { abstract Schema getSchema(); @@ -143,29 +199,220 @@ static SchemaAndDescriptor of(Schema schema, FieldAccessDescriptor fieldAccessDe } private static final Map CACHED_SELECTORS = - Maps.newConcurrentMap(); + new ConcurrentHashMap<>(); + + // Non-evicting bounded cache so generated selector classes never thrash Metaspace; descriptors + // past MAX_GENERATED_SELECTOR_CLASSES fall back cleanly to FlatRowSelector / SelectHelpers. + private static final Map> + CACHED_SELECTOR_CONSTRUCTORS = new ConcurrentHashMap<>(); + private static final AtomicInteger GENERATED_SELECTOR_COUNT = new AtomicInteger(); static RowSelector getRowSelector( Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor) { return CACHED_SELECTORS.computeIfAbsent( SchemaAndDescriptor.of(inputSchema, fieldAccessDescriptor), - SelectByteBuddyHelpers::createRowSelector); + key -> + createRowSelectorForOutputSchema( + key.getSchema(), + key.getFieldAccessDecriptor(), + SelectHelpers.getOutputSchema(key.getSchema(), key.getFieldAccessDecriptor()))); + } + + static RowSelector getRowSelector( + Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor, Schema outputSchema) { + return createRowSelectorForOutputSchema(inputSchema, fieldAccessDescriptor, outputSchema); } - static RowSelector createRowSelector(SchemaAndDescriptor schemaAndDescriptor) { - Schema outputSchema = - SelectHelpers.getOutputSchema( - schemaAndDescriptor.getSchema(), schemaAndDescriptor.getFieldAccessDecriptor()); + private static RowSelector createRowSelectorForOutputSchema( + Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor, Schema outputSchema) { + // 1. Empty selection fast path. + int outputFieldCount = outputSchema.getFieldCount(); + if (outputFieldCount == 0) { + final Row emptyRow = Row.attachValues(outputSchema, new Object[0]); + return input -> emptyRow; + } + + // 2. Top-level wildcard (*) fast path. + if (fieldAccessDescriptor.getAllFields()) { + if (outputSchema == inputSchema || inputSchema.equals(outputSchema)) { + return input -> input == null ? Row.nullRow(outputSchema) : input; + } + return new RewrapRowSelector(outputSchema); + } + + // 3. Single nested wildcard (e.g. "nested.*") fast path (without LIST/MAP qualifiers). + if (fieldAccessDescriptor.getFieldsAccessed().isEmpty() + && fieldAccessDescriptor.getNestedFieldsAccessed().size() == 1) { + Map.Entry only = + fieldAccessDescriptor.getNestedFieldsAccessed().entrySet().iterator().next(); + FieldDescriptor fd = only.getKey(); + if (fd.getQualifiers().isEmpty() && only.getValue().getAllFields()) { + int fieldId = fd.getFieldId(); + Schema nestedSchema = inputSchema.getField(fieldId).getType().getRowSchema(); + boolean schemaMatches = outputSchema == nestedSchema || outputSchema.equals(nestedSchema); + return new SingleNestedWildcardSelector(fieldId, outputSchema, schemaMatches); + } + } + + // 4. Wide flat/nested/container guard to avoid exceeding C2 HugeMethodLimit / 64KB limit. + if (estimateBytecodeBytes(inputSchema, fieldAccessDescriptor) > MAX_ESTIMATED_BYTECODE_BYTES) { + return fallbackSelector(inputSchema, fieldAccessDescriptor, outputSchema); + } + + SchemaAndDescriptor key = SchemaAndDescriptor.of(inputSchema, fieldAccessDescriptor); + Constructor ctor = CACHED_SELECTOR_CONSTRUCTORS.get(key); + if (ctor == null) { + if (GENERATED_SELECTOR_COUNT.get() >= MAX_GENERATED_SELECTOR_CLASSES) { + return fallbackSelector(inputSchema, fieldAccessDescriptor, outputSchema); + } + ctor = + CACHED_SELECTOR_CONSTRUCTORS.computeIfAbsent( + key, + k -> { + if (GENERATED_SELECTOR_COUNT.incrementAndGet() > MAX_GENERATED_SELECTOR_CLASSES) { + return null; + } + return compileRowSelectorClass(k.getSchema(), k.getFieldAccessDecriptor()); + }); + if (ctor == null) { + return fallbackSelector(inputSchema, fieldAccessDescriptor, outputSchema); + } + } + try { + return ctor.newInstance(outputSchema); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException("Unable to instantiate generated RowSelector", e); + } + } + + private static RowSelector fallbackSelector( + Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor, Schema outputSchema) { + if (fieldAccessDescriptor.getNestedFieldsAccessed().isEmpty()) { + int[] ids = + fieldAccessDescriptor.fieldIdsAccessed().stream().mapToInt(Integer::intValue).toArray(); + return new FlatRowSelector(ids, outputSchema); + } + return SelectHelpers.getRowSelector(inputSchema, fieldAccessDescriptor, outputSchema); + } + + private static int estimateBytecodeBytes(Schema inputSchema, FieldAccessDescriptor descriptor) { + if (descriptor.getAllFields()) { + return inputSchema.getFieldCount() * 24; + } + int bytes = descriptor.getFieldsAccessed().size() * 24; + for (Map.Entry nested : + descriptor.getNestedFieldsAccessed().entrySet()) { + FieldDescriptor fd = nested.getKey(); + FieldType type = inputSchema.getField(fd.getFieldId()).getType(); + List qualifiers = fd.getQualifiers(); + bytes += 40; + for (Qualifier q : qualifiers) { + switch (q.getKind()) { + case LIST: + bytes += 120; + type = checkNotNull(type.getCollectionElementType()); + break; + case MAP: + bytes += 140; + type = checkNotNull(type.getMapValueType()); + break; + default: + throw new RuntimeException("Unexpected type " + q.getKind()); + } + } + bytes += estimateBytecodeBytes(checkNotNull(type.getRowSchema()), nested.getValue()); + if (bytes > MAX_ESTIMATED_BYTECODE_BYTES) { + return bytes; + } + } + return bytes; + } + + private static final class RewrapRowSelector implements RowSelector { + private final Schema outputSchema; + + RewrapRowSelector(Schema outputSchema) { + this.outputSchema = outputSchema; + } + + @Override + public Row select(Row input) { + if (input == null) { + return Row.nullRow(outputSchema); + } + return SelectHelpers.rewrapRow(input, outputSchema); + } + } + + private static final class SingleNestedWildcardSelector implements RowSelector { + private final int fieldId; + private final Schema outputSchema; + private final boolean schemaMatches; + + SingleNestedWildcardSelector(int fieldId, Schema outputSchema, boolean schemaMatches) { + this.fieldId = fieldId; + this.outputSchema = outputSchema; + this.schemaMatches = schemaMatches; + } + + @Override + public Row select(Row input) { + if (input == null) { + return Row.nullRow(outputSchema); + } + Row nested = input.getValue(fieldId); + if (nested == null) { + return Row.nullRow(outputSchema); + } + if (schemaMatches) { + return nested; + } + return SelectHelpers.rewrapRow(nested, outputSchema); + } + } + + private static final class FlatRowSelector implements RowSelector { + private final int[] fieldIds; + private final Schema outputSchema; + + FlatRowSelector(int[] fieldIds, Schema outputSchema) { + this.fieldIds = fieldIds; + this.outputSchema = outputSchema; + } + + @Override + public Row select(Row input) { + int n = fieldIds.length; + Object[] out = new Object[n]; + if (input == null) { + return Row.attachValues(outputSchema, out); + } + if (input instanceof RowWithStorage) { + @Nullable Object @Nullable [] raw = ((RowWithStorage) input).getRawArray(); + if (raw != null) { + for (int i = 0; i < n; i++) { + out[i] = raw[fieldIds[i]]; + } + return Row.attachValues(outputSchema, out); + } + } + for (int i = 0; i < n; i++) { + out[i] = input.getValue(fieldIds[i]); + } + return Row.attachValues(outputSchema, out); + } + } + + private static Constructor compileRowSelectorClass( + Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor) { + int outputFieldCount = SelectHelpers.countRowFields(inputSchema, fieldAccessDescriptor); try { DynamicType.Builder builder = BYTE_BUDDY .subclass(RowSelector.class) .method(ElementMatchers.named("select")) .intercept( - new SelectInstruction( - schemaAndDescriptor.getFieldAccessDecriptor(), - schemaAndDescriptor.getSchema(), - outputSchema)) + new SelectInstruction(fieldAccessDescriptor, inputSchema, outputFieldCount)) .defineField( SELECT_SCHEMA_FIELD_NAME, Schema.class, @@ -182,13 +429,9 @@ static RowSelector createRowSelector(SchemaAndDescriptor schemaAndDescriptor) { ReflectHelpers.findClassLoader(Row.class.getClassLoader()), getClassLoadingStrategy(RowSelector.class)) .getLoaded() - .getDeclaredConstructor(Schema.class) - .newInstance(outputSchema); - } catch (InstantiationException - | IllegalAccessException - | NoSuchMethodException - | InvocationTargetException e) { - throw new RuntimeException("Unable to generate"); + .getDeclaredConstructor(Schema.class); + } catch (NoSuchMethodException e) { + throw new RuntimeException("Unable to generate RowSelector", e); } } @@ -232,16 +475,21 @@ public ByteCodeAppender appender(final Target implementationTarget) { private static class ArrayManager { private final StackManipulation.Size sizeDecreaseArrayStore; private final int arraySize; + private final boolean reused; int currentArrayField = 0; - ArrayManager(int arraySize) { - // Size decreases by index and array reference (2) and array element (1, 2) after each element - // storage. + ArrayManager(int arraySize, boolean reused) { + // Size decreases by index and array reference (2) and array element (1) after each store. this.sizeDecreaseArrayStore = StackSize.DOUBLE .toDecreasingSize() .aggregate(Generic.OBJECT.getStackSize().toDecreasingSize()); this.arraySize = arraySize; + this.reused = reused; + } + + boolean isReused() { + return reused; } StackManipulation createArray() { @@ -293,13 +541,26 @@ public StackManipulation.Size apply(MethodVisitor methodVisitor, Context context } }; } + + StackManipulation.Size emitClearRange( + int fromIndex, int toIndex, MethodVisitor mv, Context ctx) { + if (fromIndex >= toIndex) { + return new StackManipulation.Size(0, 0); + } + return new StackManipulation.Compound( + Duplication.SINGLE, + IntegerConstant.forValue(fromIndex), + IntegerConstant.forValue(toIndex), + MethodInvocation.invoke(CLEAR_RANGE)) + .apply(mv, ctx); + } } private static class SelectInstruction implements Implementation { private final FieldAccessDescriptor fieldAccessDescriptor; private final Schema inputSchema; - private final Schema outputSchema; - private ByteBuddyLocalVariableManager localVariables; + private final int outputFieldCount; + private final ByteBuddyLocalVariableManager localVariables; private static final int INPUT_ROW_ARG = 1; private final int currentSelectRowArg; private final int fieldValueArg; @@ -307,10 +568,10 @@ private static class SelectInstruction implements Implementation { private static final int NUM_FUNCTION_ARGS = 2; // Args are this and the row to select. public SelectInstruction( - FieldAccessDescriptor fieldAccessDescriptor, Schema inputSchema, Schema outputSchema) { + FieldAccessDescriptor fieldAccessDescriptor, Schema inputSchema, int outputFieldCount) { this.fieldAccessDescriptor = fieldAccessDescriptor; this.inputSchema = inputSchema; - this.outputSchema = outputSchema; + this.outputFieldCount = outputFieldCount; this.localVariables = new ByteBuddyLocalVariableManager(NUM_FUNCTION_ARGS); currentSelectRowArg = localVariables.createVariable(); fieldValueArg = localVariables.createVariable(); @@ -327,8 +588,8 @@ public ByteCodeAppender appender(final Target implementationTarget) { int numLocals = 1 + instrumentedMethod.getParameters().size(); StackManipulation.Size size = new StackManipulation.Size(0, numLocals); - // Create the Row builder. - StackManipulation createRowBuilder = + // Push OUTPUTSCHEMA directly for Row.attachValues(Schema, Object[]) (avoids Row.Builder). + StackManipulation loadOutputSchema = new StackManipulation.Compound( MethodVariableAccess.loadThis(), FieldAccess.forField( @@ -337,25 +598,98 @@ public ByteCodeAppender appender(final Target implementationTarget) { .getDeclaredFields() .filter(ElementMatchers.named(SELECT_SCHEMA_FIELD_NAME)) .getOnly()) - .read(), - MethodInvocation.invoke( - new ForLoadedType(Row.class) - .getDeclaredMethods() - .filter(ElementMatchers.named("withSchema")) - .getOnly())); - size = size.aggregate(createRowBuilder.apply(methodVisitor, implementationContext)); + .read()); + size = size.aggregate(loadOutputSchema.apply(methodVisitor, implementationContext)); + + // Fast path for flat top-level field subset selections: direct RowWithStorage raw array + // reads avoid virtual Row.getValue(i) calls entirely. + if (fieldAccessDescriptor.getNestedFieldsAccessed().isEmpty() + && !fieldAccessDescriptor.getAllFields()) { + ArrayManager arrayManager = new ArrayManager(outputFieldCount, false); + size = + size.aggregate( + arrayManager.createArray().apply(methodVisitor, implementationContext)); + + List ids = fieldAccessDescriptor.fieldIdsAccessed(); + Label doneLabel = new Label(); + Label slowPathLabel = new Label(); + + // if (input == null) goto done (array already filled with nulls) + size = + size.aggregate( + MethodVariableAccess.REFERENCE + .loadFrom(INPUT_ROW_ARG) + .apply(methodVisitor, implementationContext)); + methodVisitor.visitJumpInsn(Opcodes.IFNULL, doneLabel); + + // Check input instanceof RowWithStorage and getRawArray() != null. + size = + size.aggregate( + MethodVariableAccess.REFERENCE + .loadFrom(INPUT_ROW_ARG) + .apply(methodVisitor, implementationContext)); + methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, ROW_WITH_STORAGE_TYPE.getInternalName()); + methodVisitor.visitJumpInsn(Opcodes.IFEQ, slowPathLabel); + + int rawArrVar = localVariables.createVariable(); + size = + size.aggregate( + new StackManipulation.Compound( + MethodVariableAccess.REFERENCE.loadFrom(INPUT_ROW_ARG), + TypeCasting.to(ROW_WITH_STORAGE_TYPE), + MethodInvocation.invoke(ROW_WITH_STORAGE_RAW_ARRAY), + Duplication.SINGLE, + localVariables.writeVariable(rawArrVar)) + .apply(methodVisitor, implementationContext)); + methodVisitor.visitJumpInsn(Opcodes.IFNULL, slowPathLabel); + + // Fast array-to-array copy. + for (int i = 0; i < ids.size(); i++) { + StackManipulation readRaw = + new StackManipulation.Compound( + localVariables.readVariable(rawArrVar), + IntegerConstant.forValue(ids.get(i)), + ArrayAccess.REFERENCE.load()); + size = + size.aggregate( + arrayManager.store(i, readRaw).apply(methodVisitor, implementationContext)); + } + methodVisitor.visitJumpInsn(Opcodes.GOTO, doneLabel); + + // Slow path: invoke Row.getValue(id) for each selected field (no per-field null checks). + methodVisitor.visitLabel(slowPathLabel); + for (int i = 0; i < ids.size(); i++) { + StackManipulation readVirtual = + new StackManipulation.Compound( + MethodVariableAccess.REFERENCE.loadFrom(INPUT_ROW_ARG), + IntegerConstant.forValue(ids.get(i)), + MethodInvocation.invoke(ROW_GET_VALUE)); + size = + size.aggregate( + arrayManager.store(i, readVirtual).apply(methodVisitor, implementationContext)); + } + + methodVisitor.visitLabel(doneLabel); + StackManipulation attachAndReturn = + new StackManipulation.Compound( + MethodInvocation.invoke(ROW_ATTACH_VALUES), MethodReturn.REFERENCE); + size = size.aggregate(attachAndReturn.apply(methodVisitor, implementationContext)); + return new ByteCodeAppender.Size( + Math.max(size.getMaximalSize(), 6), localVariables.getTotalNumVariables()); + } - // Create a new object array with one entry for each field in the output schema. - ArrayManager arrayManager = new ArrayManager(outputSchema.getFieldCount()); + // General path (handles arbitrary nesting, lists, iterables, maps, null sub-rows). + ArrayManager arrayManager = new ArrayManager(outputFieldCount, false); size = size.aggregate(arrayManager.createArray().apply(methodVisitor, implementationContext)); - // Store the current input row into a local variable. - StackManipulation storeRowInLocalVariable = - localVariables.copy(INPUT_ROW_ARG, currentSelectRowArg); - size = size.aggregate(storeRowInLocalVariable.apply(methodVisitor, implementationContext)); + // Store the current input row into currentSelectRowArg (already statically typed Row). + size = + size.aggregate( + localVariables + .copy(INPUT_ROW_ARG, currentSelectRowArg) + .apply(methodVisitor, implementationContext)); - // Fill the array values with those selected from the row. size = size.aggregate( selectIntoArray( @@ -365,46 +699,25 @@ public ByteCodeAppender appender(final Target implementationTarget) { methodVisitor, implementationContext)); - // Return the actual row. StackManipulation attachToRow = new StackManipulation.Compound( - MethodInvocation.invoke( - new ForLoadedType(Row.Builder.class) - .getDeclaredMethods() - .filter( - ElementMatchers.named("attachValues") - .and(ElementMatchers.takesArguments(Object[].class))) - .getOnly()), - MethodReturn.REFERENCE); + MethodInvocation.invoke(ROW_ATTACH_VALUES), MethodReturn.REFERENCE); size = size.aggregate(attachToRow.apply(methodVisitor, implementationContext)); return new ByteCodeAppender.Size( - size.getMaximalSize(), localVariables.getTotalNumVariables()); + Math.max(size.getMaximalSize(), 8), localVariables.getTotalNumVariables()); }; } - // Selects a field from the current row being selected (the one stored in - // currentSelectRowArg). - private StackManipulation getCurrentRowFieldValue(int i) { - StackManipulation readRow = localVariables.readVariable(currentSelectRowArg, Row.class); - StackManipulation getValue = - new StackManipulation.Compound( - localVariables.readVariable(currentSelectRowArg, Row.class), - IntegerConstant.forValue(i), - MethodInvocation.invoke( - ROW_LOADED_TYPE - .getDeclaredMethods() - .filter( - ElementMatchers.named("getValue") - .and(ElementMatchers.takesArguments(int.class))) - .getOnly())); - - return new ShortCircuitReturnNull(readRow, getValue); - } - - // Generate bytecode to select all specified fields from the Row. The current row being selected - // is stored - // in the local variable at position 2. The current array being written to is at the top of the - // stack. + // Read a field directly from the non-null Row in currentSelectRowArg. + private StackManipulation getNonNullCurrentRowFieldValue(int fieldId) { + return new StackManipulation.Compound( + localVariables.readVariable(currentSelectRowArg), + IntegerConstant.forValue(fieldId), + MethodInvocation.invoke(ROW_GET_VALUE)); + } + + // Generate bytecode to select all specified fields from the Row in currentSelectRowArg. + // Performs ONE null check per sub-row instead of per-field null checks and checkcasts. StackManipulation.Size selectIntoArray( Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor, @@ -412,54 +725,78 @@ StackManipulation.Size selectIntoArray( MethodVisitor methodVisitor, Context implementationContext) { StackManipulation.Size size = new StackManipulation.Size(0, 0); + int startSlot = arrayManager.currentArrayField; + + Label nullRowLabel = new Label(); + Label doneLabel = new Label(); + + // Single null check for the entire (sub-)row. + size = + size.aggregate( + localVariables + .readVariable(currentSelectRowArg) + .apply(methodVisitor, implementationContext)); + methodVisitor.visitJumpInsn(Opcodes.IFNULL, nullRowLabel); + if (fieldAccessDescriptor.getAllFields()) { - StackManipulation storeAllValues = - new StackManipulation.Compound( - IntStream.range(0, inputSchema.getFieldCount()) - .mapToObj(i -> arrayManager.append(getCurrentRowFieldValue(i))) - .collect(Collectors.toList())); - return size.aggregate(storeAllValues.apply(methodVisitor, implementationContext)); + for (int i = 0; i < inputSchema.getFieldCount(); i++) { + size = + size.aggregate( + arrayManager + .append(getNonNullCurrentRowFieldValue(i)) + .apply(methodVisitor, implementationContext)); + } + } else { + for (int i : fieldAccessDescriptor.fieldIdsAccessed()) { + size = + size.aggregate( + arrayManager + .append(getNonNullCurrentRowFieldValue(i)) + .apply(methodVisitor, implementationContext)); + } + + for (Map.Entry nested : + fieldAccessDescriptor.getNestedFieldsAccessed().entrySet()) { + FieldDescriptor field = nested.getKey(); + FieldAccessDescriptor nestedAccess = nested.getValue(); + FieldType nestedInputType = inputSchema.getField(field.getFieldId()).getType(); + + size = + size.aggregate( + selectIntoArrayHelper( + field.getQualifiers(), + 0, + field.getFieldId(), + nestedAccess, + nestedInputType, + arrayManager, + methodVisitor, + implementationContext)); + } } - StackManipulation storeAllValues = - new StackManipulation.Compound( - fieldAccessDescriptor.fieldIdsAccessed().stream() - .map(i -> arrayManager.append(getCurrentRowFieldValue(i))) - .collect(Collectors.toList())); - size = size.aggregate(storeAllValues.apply(methodVisitor, implementationContext)); - - for (Map.Entry nested : - fieldAccessDescriptor.getNestedFieldsAccessed().entrySet()) { - FieldDescriptor field = nested.getKey(); - FieldAccessDescriptor nestedAccess = nested.getValue(); - FieldType nestedInputType = inputSchema.getField(field.getFieldId()).getType(); - - StackManipulation.Size subSelectSize = - selectIntoArrayHelper( - field.getQualifiers(), - 0, - field.getFieldId(), - nestedAccess, - nestedInputType, - arrayManager, - methodVisitor, - implementationContext); - size = size.aggregate(subSelectSize); + int endSlot = arrayManager.currentArrayField; + if (arrayManager.isReused() && endSlot > startSlot) { + methodVisitor.visitJumpInsn(Opcodes.GOTO, doneLabel); + methodVisitor.visitLabel(nullRowLabel); + size = + size.aggregate( + arrayManager.emitClearRange( + startSlot, endSlot, methodVisitor, implementationContext)); + methodVisitor.visitLabel(doneLabel); + } else { + // Fresh Object[] is already zero-initialized to null at every slot. + methodVisitor.visitLabel(nullRowLabel); } return size; } - // Load the current field value to process. If a fieldId is specified, then we assume that we - // need to select - // a field from the Row stored in currentSelectRowArg. Otherwise we assume that the value has - // already been stored - // in fieldValueArg, and we read from there. + // Load the current field value to process. If fieldId != -1, read from the non-null Row + // stored in currentSelectRowArg; otherwise read from fieldValueArg. private StackManipulation loadFieldValue(int fieldId) { if (fieldId != -1) { - // If a field id was specified, then load it. - return getCurrentRowFieldValue(fieldId); + return getNonNullCurrentRowFieldValue(fieldId); } else { - // If not specified, then assume it was stored in this member variable. return localVariables.readVariable(fieldValueArg); } } @@ -476,15 +813,14 @@ private StackManipulation.Size selectIntoArrayHelper( StackManipulation.Size size = new StackManipulation.Size(0, 0); if (qualifierPosition >= qualifiers.size()) { - // We have already constructed all arrays and maps. What remains must be a Row. + // Cast to Row ONCE on entering this sub-row, rather than on every field read. ByteBuddyLocalVariableManager.BackupLocalVariable backup = localVariables.backupVariable(currentSelectRowArg); StackManipulation updateLocalVariable = new StackManipulation.Compound( loadFieldValue(fieldId), - // Backup the current value of the currentSelectRowArg variable. + TypeCasting.to(ROW_LOADED_TYPE), backup.backup(), - // Update the row local with the current stack value. localVariables.writeVariable(currentSelectRowArg)); size = size.aggregate(updateLocalVariable.apply(methodVisitor, implementationContext)); @@ -496,7 +832,6 @@ private StackManipulation.Size selectIntoArrayHelper( arrayManager, methodVisitor, implementationContext)); - // Restore the value of currentSelectRowArg from the temp variable. size = size.aggregate(backup.restore().apply(methodVisitor, implementationContext)); return size; } @@ -543,103 +878,92 @@ private StackManipulation.Size processList( Context implementationContext) { StackManipulation.Size size = new StackManipulation.Size(0, 0); FieldType nestedInputType = checkNotNull(inputType.getCollectionElementType()); - Schema nestedSchema = getNestedSchema(nestedInputType, fieldAccessDescriptor); - - // We create temp local variables to store all the arrays we create. Each field in - // nestedSchema corresponds to a separate array in the output. - int[] localVariablesForArrays = - IntStream.range(0, nestedSchema.getFieldCount()) - .map(i -> localVariables.createVariable()) - .toArray(); - // Each field returned in nestedSchema will become it's own list in the output. So let's - // iterate and create arrays and store each one in the output. - StackManipulation createAllArrayLists = - new StackManipulation.Compound( - Arrays.stream(localVariablesForArrays) - .mapToObj( - v -> { - StackManipulation createArrayList = - new StackManipulation.Compound( - MethodInvocation.invoke(LISTS_NEW_ARRAYLIST), - // Store the ArrayList in a local variable. - Duplication.SINGLE, - localVariables.writeVariable(v)); - StackManipulation storeNull = - new StackManipulation.Compound( - NullConstant.INSTANCE, - localVariables.writeVariable(v), - NullConstant.INSTANCE); - - // Create the array only if the input isn't null. Otherwise store a null - // value into the output - // array. - int arraySlot = arrayManager.reserveSlot(); - return new IfNullElse( - loadFieldValue(fieldId), - arrayManager.store(arraySlot, storeNull), - arrayManager.store(arraySlot, createArrayList)); - }) - .collect(Collectors.toList())); - size = size.aggregate(createAllArrayLists.apply(methodVisitor, implementationContext)); - - // If the input variable is null, then don't try and iterate over it. + int nestedFieldCount = + SelectHelpers.countFields( + nestedInputType, qualifiers, qualifierPosition + 1, fieldAccessDescriptor); + + int startSlot = arrayManager.currentArrayField; + int[] outputSlots = new int[nestedFieldCount]; + int[] localVariablesForArrays = new int[nestedFieldCount]; + for (int i = 0; i < nestedFieldCount; i++) { + outputSlots[i] = arrayManager.reserveSlot(); + localVariablesForArrays[i] = localVariables.createVariable(); + } + + // Read the container ONCE and cast to Iterable. + int iterableVar = localVariables.createVariable(); + size = + size.aggregate( + new StackManipulation.Compound( + loadFieldValue(fieldId), + TypeCasting.to(ITERABLE_LOADED_TYPE), + Duplication.SINGLE, + localVariables.writeVariable(iterableVar)) + .apply(methodVisitor, implementationContext)); + Label onNullLabel = new Label(); - size = size.aggregate(loadFieldValue(fieldId).apply(methodVisitor, implementationContext)); + Label doneLabel = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNULL, onNullLabel); - size = size.aggregate(StackSize.SINGLE.toDecreasingSize()); - // Now iterate over the value, selecting from each element. - StackManipulation readListIterator = - new StackManipulation.Compound( - loadFieldValue(fieldId), - TypeCasting.to(new ForLoadedType(Iterable.class)), - MethodInvocation.invoke(ITERABLE_ITERATOR)); - size = size.aggregate(readListIterator.apply(methodVisitor, implementationContext)); + // Allocate K pre-sized ArrayLists once and store them into output slots + locals. + for (int i = 0; i < nestedFieldCount; i++) { + StackManipulation createList = + new StackManipulation.Compound( + localVariables.readVariable(iterableVar), + MethodInvocation.invoke(NEW_LIST_FOR_ITERABLE), + Duplication.SINGLE, + localVariables.writeVariable(localVariablesForArrays[i])); + size = + size.aggregate( + arrayManager + .store(outputSlots[i], createList) + .apply(methodVisitor, implementationContext)); + } + + // Allocate a single reusable scratch Object[nestedFieldCount] outside the loop. + ArrayManager nestedArrayManager = new ArrayManager(nestedFieldCount, true); + int scratchArrayVar = localVariables.createVariable(); + size = + size.aggregate( + new StackManipulation.Compound( + nestedArrayManager.createArray(), + localVariables.writeVariable(scratchArrayVar)) + .apply(methodVisitor, implementationContext)); + + // Obtain iterator from iterableVar. + size = + size.aggregate( + new StackManipulation.Compound( + localVariables.readVariable(iterableVar), + MethodInvocation.invoke(ITERABLE_ITERATOR)) + .apply(methodVisitor, implementationContext)); Label startLoopLabel = new Label(); Label exitLoopLabel = new Label(); - // Loop over the entire iterable. methodVisitor.visitLabel(startLoopLabel); - StackManipulation checkTerminationCondition = - new StackManipulation.Compound( - Duplication.SINGLE, MethodInvocation.invoke(ITERATOR_HASNEXT)); - size = size.aggregate(checkTerminationCondition.apply(methodVisitor, implementationContext)); - methodVisitor.visitJumpInsn(Opcodes.IFEQ, exitLoopLabel); // Exit the loop if !hasNext(). - size = size.aggregate(StackSize.SINGLE.toDecreasingSize()); - - // Read the next value in the iterator. - StackManipulation getNext = - new StackManipulation.Compound( - Duplication.SINGLE, MethodInvocation.invoke(ITERATOR_NEXT)); - size = size.aggregate(getNext.apply(methodVisitor, implementationContext)); - - ByteBuddyLocalVariableManager.BackupLocalVariable backupFieldValue = null; - if (fieldId == -1) { - // Save the field value arg before overwriting it, as we need it in subsequent - // iterations of the - // loop. - backupFieldValue = localVariables.backupVariable(fieldValueArg); - size = - size.aggregate(backupFieldValue.backup().apply(methodVisitor, implementationContext)); - } - - // Recursively generate select with one qualifier consumed. Since we pass in -1 as the - // field id, the iterator.next() value will be consumed as the value to select instead - // of accessing the fieldId. size = size.aggregate( - localVariables - .writeVariable(fieldValueArg) + new StackManipulation.Compound( + Duplication.SINGLE, MethodInvocation.invoke(ITERATOR_HASNEXT)) .apply(methodVisitor, implementationContext)); + methodVisitor.visitJumpInsn(Opcodes.IFEQ, exitLoopLabel); - // Select the fields of interest from this row. - // Create a new object array with one entry for each field selected from this row. - ArrayManager nestedArrayManager = new ArrayManager(nestedSchema.getFieldCount()); + // Read next element and save in fieldValueArg for the recursive select. size = size.aggregate( - nestedArrayManager.createArray().apply(methodVisitor, implementationContext)); + new StackManipulation.Compound( + Duplication.SINGLE, + MethodInvocation.invoke(ITERATOR_NEXT), + localVariables.writeVariable(fieldValueArg)) + .apply(methodVisitor, implementationContext)); + // Push scratch array, populate it (with reused-array null clearing), and distribute fields. + size = + size.aggregate( + localVariables + .readVariable(scratchArrayVar) + .apply(methodVisitor, implementationContext)); size = size.aggregate( selectIntoArrayHelper( @@ -652,51 +976,38 @@ private StackManipulation.Size processList( methodVisitor, implementationContext)); - if (backupFieldValue != null) { - // Restore the field value. - size = - size.aggregate(backupFieldValue.restore().apply(methodVisitor, implementationContext)); - } - - // Now the top of the stack holds an array containing all the fields selected from the - // row. - // Now we need to distribute these fields into the separate arrays we created in the - // result. - // That is: if this select returned {a, b}, our final resulting schema will contain two - // lists, - // so we must add a to the first and b to the second list. - - int tempVariableForField = localVariables.createVariable(); - for (int i = 0; i < nestedSchema.getFieldCount(); ++i) { - // Extract the field and store it in a temp variable. - StackManipulation extractField = - new StackManipulation.Compound( - Duplication.SINGLE, - IntegerConstant.forValue(i), - ArrayAccess.REFERENCE.load(), - localVariables.writeVariable(tempVariableForField)); - StackManipulation addItemToList = - new StackManipulation.Compound( - localVariables.readVariable(localVariablesForArrays[i]), - localVariables.readVariable(tempVariableForField), - MethodInvocation.invoke(LIST_ADD), - // Ignore return value from add(). - Removal.SINGLE); + for (int i = 0; i < nestedFieldCount; i++) { size = size.aggregate( - new StackManipulation.Compound(extractField, addItemToList) + new StackManipulation.Compound( + localVariables.readVariable(localVariablesForArrays[i]), + localVariables.readVariable(scratchArrayVar), + IntegerConstant.forValue(i), + ArrayAccess.REFERENCE.load(), + MethodInvocation.invoke(ARRAY_LIST_ADD), + Removal.SINGLE) .apply(methodVisitor, implementationContext)); } - - // Pop the created array from the top of the stack. + // Pop the scratch array pushed before selectIntoArrayHelper. size = size.aggregate(Removal.SINGLE.apply(methodVisitor, implementationContext)); - // Go back to the beginning of the loop. methodVisitor.visitJumpInsn(Opcodes.GOTO, startLoopLabel); methodVisitor.visitLabel(exitLoopLabel); - // Remove the iterator from the top of the stack. + // Pop the iterator. size = size.aggregate(Removal.SINGLE.apply(methodVisitor, implementationContext)); - methodVisitor.visitLabel(onNullLabel); + + int endSlot = arrayManager.currentArrayField; + if (arrayManager.isReused() && endSlot > startSlot) { + methodVisitor.visitJumpInsn(Opcodes.GOTO, doneLabel); + methodVisitor.visitLabel(onNullLabel); + size = + size.aggregate( + arrayManager.emitClearRange( + startSlot, endSlot, methodVisitor, implementationContext)); + methodVisitor.visitLabel(doneLabel); + } else { + methodVisitor.visitLabel(onNullLabel); + } return size; } @@ -711,109 +1022,98 @@ private StackManipulation.Size processMap( Context implementationContext) { StackManipulation.Size size = new StackManipulation.Size(0, 0); FieldType nestedInputType = checkNotNull(inputType.getMapValueType()); - Schema nestedSchema = getNestedSchema(nestedInputType, fieldAccessDescriptor); - - // We create temp local variables to store all the maps we create. Each field in - // nestedSchema corresponds to a separate array in the output. - int[] localVariablesForMaps = - IntStream.range(0, nestedSchema.getFieldCount()) - .map(i -> localVariables.createVariable()) - .toArray(); - - // Each field returned in nestedSchema will become it's own map in the output. So let's - // iterate and create arrays and store each one in the output. - StackManipulation createAllHashMaps = - new StackManipulation.Compound( - Arrays.stream(localVariablesForMaps) - .mapToObj( - v -> { - StackManipulation createHashMap = - new StackManipulation.Compound( - MethodInvocation.invoke(MAPS_NEW_HASHMAP), - // Store the HashMap in a local variable. - Duplication.SINGLE, - localVariables.writeVariable(v)); - StackManipulation storeNull = - new StackManipulation.Compound( - NullConstant.INSTANCE, - localVariables.writeVariable(v), - NullConstant.INSTANCE); - int arraySlot = arrayManager.reserveSlot(); - return new IfNullElse( - loadFieldValue(fieldId), - arrayManager.store(arraySlot, storeNull), - arrayManager.store(arraySlot, createHashMap)); - }) - .collect(Collectors.toList())); - size = size.aggregate(createAllHashMaps.apply(methodVisitor, implementationContext)); - - // If the input variable is null, then don't try and iterate over it. + int nestedFieldCount = + SelectHelpers.countFields( + nestedInputType, qualifiers, qualifierPosition + 1, fieldAccessDescriptor); + + int startSlot = arrayManager.currentArrayField; + int[] outputSlots = new int[nestedFieldCount]; + int[] localVariablesForMaps = new int[nestedFieldCount]; + for (int i = 0; i < nestedFieldCount; i++) { + outputSlots[i] = arrayManager.reserveSlot(); + localVariablesForMaps[i] = localVariables.createVariable(); + } + + // Read the map ONCE and cast to Map. + int mapVar = localVariables.createVariable(); + size = + size.aggregate( + new StackManipulation.Compound( + loadFieldValue(fieldId), + TypeCasting.to(MAP_LOADED_TYPE), + Duplication.SINGLE, + localVariables.writeVariable(mapVar)) + .apply(methodVisitor, implementationContext)); + Label onNullLabel = new Label(); - size = size.aggregate(loadFieldValue(fieldId).apply(methodVisitor, implementationContext)); + Label doneLabel = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNULL, onNullLabel); - size = size.aggregate(StackSize.SINGLE.toDecreasingSize()); - - // Now iterate over the value, selecting from each element. - StackManipulation readMapEntriesIterator = - new StackManipulation.Compound( - loadFieldValue(fieldId), - TypeCasting.to(new ForLoadedType(Map.class)), - MethodInvocation.invoke(MAP_ENTRYSET), - MethodInvocation.invoke(ITERABLE_ITERATOR)); - size = size.aggregate(readMapEntriesIterator.apply(methodVisitor, implementationContext)); - - // Loop over the entire entrySet iterable. + + // Allocate K pre-sized HashMaps once and store them into output slots + locals. + for (int i = 0; i < nestedFieldCount; i++) { + StackManipulation createMap = + new StackManipulation.Compound( + localVariables.readVariable(mapVar), + MethodInvocation.invoke(NEW_MAP_FOR_MAP), + Duplication.SINGLE, + localVariables.writeVariable(localVariablesForMaps[i])); + size = + size.aggregate( + arrayManager + .store(outputSlots[i], createMap) + .apply(methodVisitor, implementationContext)); + } + + // Allocate a single reusable scratch Object[nestedFieldCount] outside the loop. + ArrayManager nestedArrayManager = new ArrayManager(nestedFieldCount, true); + int scratchArrayVar = localVariables.createVariable(); + size = + size.aggregate( + new StackManipulation.Compound( + nestedArrayManager.createArray(), + localVariables.writeVariable(scratchArrayVar)) + .apply(methodVisitor, implementationContext)); + + // Obtain entrySet iterator from mapVar. + size = + size.aggregate( + new StackManipulation.Compound( + localVariables.readVariable(mapVar), + MethodInvocation.invoke(MAP_ENTRYSET), + MethodInvocation.invoke(ITERABLE_ITERATOR)) + .apply(methodVisitor, implementationContext)); + Label startLoopLabel = new Label(); Label exitLoopLabel = new Label(); methodVisitor.visitLabel(startLoopLabel); - StackManipulation checkTerminationCondition = - new StackManipulation.Compound( - Duplication.SINGLE, MethodInvocation.invoke(ITERATOR_HASNEXT)); - size = size.aggregate(checkTerminationCondition.apply(methodVisitor, implementationContext)); - methodVisitor.visitJumpInsn(Opcodes.IFEQ, exitLoopLabel); // Exit the loop if !hasNext(). - size = size.aggregate(StackSize.SINGLE.toDecreasingSize()); + size = + size.aggregate( + new StackManipulation.Compound( + Duplication.SINGLE, MethodInvocation.invoke(ITERATOR_HASNEXT)) + .apply(methodVisitor, implementationContext)); + methodVisitor.visitJumpInsn(Opcodes.IFEQ, exitLoopLabel); int keyVariable = localVariables.createVariable(); - // Read the next value in the iterator. - StackManipulation getNext = - new StackManipulation.Compound( - Duplication.SINGLE, - MethodInvocation.invoke(ITERATOR_NEXT), - // Get the key and store it in the keyVariable. - Duplication.SINGLE, - MethodInvocation.invoke(MAPENTRY_GETKEY), - localVariables.writeVariable(keyVariable), - // Get the value and leave it on the stack. - MethodInvocation.invoke(MAPENTRY_GETVALUE)); - size = size.aggregate(getNext.apply(methodVisitor, implementationContext)); - - ByteBuddyLocalVariableManager.BackupLocalVariable backupFieldValue = null; - if (fieldId == -1) { - // Save the field value arg before overwriting it, as we need it in subsequent - // iterations of the - // loop. - backupFieldValue = localVariables.backupVariable(fieldValueArg); - size = - size.aggregate(backupFieldValue.backup().apply(methodVisitor, implementationContext)); - } - - // Recursively generate select with one qualifier consumed. Since we pass in -1 as the - // field id, the iterator.next() value will be consumed as the value to select instead - // of accessing the fieldId. size = size.aggregate( - localVariables - .writeVariable(fieldValueArg) + new StackManipulation.Compound( + Duplication.SINGLE, + MethodInvocation.invoke(ITERATOR_NEXT), + TypeCasting.to(MAPENTRY_LOADED_TYPE), + Duplication.SINGLE, + MethodInvocation.invoke(MAPENTRY_GETKEY), + localVariables.writeVariable(keyVariable), + MethodInvocation.invoke(MAPENTRY_GETVALUE), + localVariables.writeVariable(fieldValueArg)) .apply(methodVisitor, implementationContext)); - // Select the fields of interest from this row. - // Create a new object array with one entry for each field selected from this row. - ArrayManager nestedArrayManager = new ArrayManager(nestedSchema.getFieldCount()); + // Push scratch array, populate it (with reused-array null clearing), and distribute fields. size = size.aggregate( - nestedArrayManager.createArray().apply(methodVisitor, implementationContext)); - + localVariables + .readVariable(scratchArrayVar) + .apply(methodVisitor, implementationContext)); size = size.aggregate( selectIntoArrayHelper( @@ -826,68 +1126,40 @@ private StackManipulation.Size processMap( methodVisitor, implementationContext)); - if (backupFieldValue != null) { - // Restore the field value. - size = - size.aggregate(backupFieldValue.restore().apply(methodVisitor, implementationContext)); - } - - // Now the top of the stack holds an array containing all the fields selected from the - // row. - // Now we need to distribute these fields into the separate arrays we created in the - // result. - // That is: if this select returned {a, b}, our final resulting schema will contain two - // maps, - // so we must add a to the first and b to the second map. - - int tempVariableForField = localVariables.createVariable(); - for (int i = 0; i < nestedSchema.getFieldCount(); ++i) { - // Extract the field and store it in a temp variable. - StackManipulation extractField = - new StackManipulation.Compound( - Duplication.SINGLE, - IntegerConstant.forValue(i), - ArrayAccess.REFERENCE.load(), - localVariables.writeVariable(tempVariableForField)); - StackManipulation addItemToMap = - new StackManipulation.Compound( - localVariables.readVariable(localVariablesForMaps[i]), - localVariables.readVariable(keyVariable), - localVariables.readVariable(tempVariableForField), - MethodInvocation.invoke(MAP_PUT), - // Ignore return value from add(). - Removal.SINGLE); + for (int i = 0; i < nestedFieldCount; i++) { size = size.aggregate( - new StackManipulation.Compound(extractField, addItemToMap) + new StackManipulation.Compound( + localVariables.readVariable(localVariablesForMaps[i]), + localVariables.readVariable(keyVariable), + localVariables.readVariable(scratchArrayVar), + IntegerConstant.forValue(i), + ArrayAccess.REFERENCE.load(), + MethodInvocation.invoke(HASH_MAP_PUT), + Removal.SINGLE) .apply(methodVisitor, implementationContext)); } - - // Pop the created array from the top of the stack. + // Pop the scratch array pushed before selectIntoArrayHelper. size = size.aggregate(Removal.SINGLE.apply(methodVisitor, implementationContext)); - // Go back to the beginning of the loop. methodVisitor.visitJumpInsn(Opcodes.GOTO, startLoopLabel); methodVisitor.visitLabel(exitLoopLabel); - // Remove the iterator from the top of the stack. + // Pop the iterator. size = size.aggregate(Removal.SINGLE.apply(methodVisitor, implementationContext)); - methodVisitor.visitLabel(onNullLabel); - return size; - } - private Schema getNestedSchema( - FieldType nestedInputType, FieldAccessDescriptor fieldAccessDescriptor) { - // When selecting multiple subelements under a list, we distribute the select - // resulting in multiple lists. For example, if there is a field "list" with type - // {a: string, b: int}[], selecting list.a, list.b results in a schema of type - // {a: string[], b: int[]}. This preserves the invariant that the name selected always - // appears in the top-level schema. - Schema tempSchema = Schema.builder().addField("a", nestedInputType).build(); - FieldAccessDescriptor tempAccessDescriptor = - FieldAccessDescriptor.create() - .withNestedField("a", fieldAccessDescriptor) - .resolve(tempSchema); - return SelectHelpers.getOutputSchema(tempSchema, tempAccessDescriptor); + int endSlot = arrayManager.currentArrayField; + if (arrayManager.isReused() && endSlot > startSlot) { + methodVisitor.visitJumpInsn(Opcodes.GOTO, doneLabel); + methodVisitor.visitLabel(onNullLabel); + size = + size.aggregate( + arrayManager.emitClearRange( + startSlot, endSlot, methodVisitor, implementationContext)); + methodVisitor.visitLabel(doneLabel); + } else { + methodVisitor.visitLabel(onNullLabel); + } + return size; } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectHelpers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectHelpers.java index 144bded228cb..c944c88772ec 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectHelpers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/SelectHelpers.java @@ -21,7 +21,8 @@ import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; -import java.util.Collections; +import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; @@ -35,9 +36,12 @@ import org.apache.beam.sdk.schemas.Schema.TypeName; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.RowWithGetters; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; +import org.checkerframework.checker.nullness.qual.Nullable; /** Helper methods to select subrows out of rows. */ @SuppressWarnings({ @@ -209,102 +213,199 @@ public static RowSelector getRowSelectorOptimized( return SelectByteBuddyHelpers.getRowSelector(inputSchema, fieldAccessDescriptor); } + @org.apache.beam.sdk.annotations.Internal + public static RowSelector getRowSelectorOptimized( + Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor, Schema outputSchema) { + return SelectByteBuddyHelpers.getRowSelector(inputSchema, fieldAccessDescriptor, outputSchema); + } + public static RowSelector getRowSelector( Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor) { Schema outputSchema = getOutputSchema(inputSchema, fieldAccessDescriptor); + return getRowSelector(inputSchema, fieldAccessDescriptor, outputSchema); + } + + @org.apache.beam.sdk.annotations.Internal + public static RowSelector getRowSelector( + Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor, Schema outputSchema) { return input -> selectRow(input, fieldAccessDescriptor, inputSchema, outputSchema); } public static class RowSelectorContainer implements RowSelector, Serializable { - private transient RowSelector rowSelector; + private transient volatile @Nullable RowSelector rowSelector; private final Schema inputSchema; private final FieldAccessDescriptor fieldAccessDescriptor; + private final @Nullable Schema outputSchema; private final boolean optimized; public RowSelectorContainer( Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor, boolean optimized) { + this(inputSchema, fieldAccessDescriptor, null, optimized); + } + + @org.apache.beam.sdk.annotations.Internal + public RowSelectorContainer( + Schema inputSchema, + FieldAccessDescriptor fieldAccessDescriptor, + @Nullable Schema outputSchema, + boolean optimized) { this.inputSchema = inputSchema; this.fieldAccessDescriptor = fieldAccessDescriptor; + this.outputSchema = outputSchema; this.optimized = optimized; } + @org.apache.beam.sdk.annotations.Internal + public RowSelector getOrCreateSelector() { + RowSelector selector = this.rowSelector; + if (selector == null) { + if (outputSchema != null) { + selector = + optimized + ? getRowSelectorOptimized(inputSchema, fieldAccessDescriptor, outputSchema) + : getRowSelector(inputSchema, fieldAccessDescriptor, outputSchema); + } else { + selector = + optimized + ? getRowSelectorOptimized(inputSchema, fieldAccessDescriptor) + : getRowSelector(inputSchema, fieldAccessDescriptor); + } + this.rowSelector = selector; + } + return selector; + } + @Override public Row select(Row input) { - if (this.rowSelector == null) { - rowSelector = - optimized - ? getRowSelectorOptimized(inputSchema, fieldAccessDescriptor) - : getRowSelector(inputSchema, fieldAccessDescriptor); - } - return rowSelector.select(input); + return getOrCreateSelector().select(input); } } /** Select a sub Row from an input Row. */ + @SuppressWarnings("ReferenceEquality") private static Row selectRow( Row input, FieldAccessDescriptor fieldAccessDescriptor, Schema inputSchema, Schema outputSchema) { if (fieldAccessDescriptor.getAllFields()) { - return input; + if (input == null) { + return Row.nullRow(outputSchema); + } + if (outputSchema == inputSchema || inputSchema.equals(outputSchema)) { + return input; + } + return rewrapRow(input, outputSchema); } - Row.Builder output = Row.withSchema(outputSchema); - selectIntoRow(inputSchema, input, output, fieldAccessDescriptor); - return output.build(); + List outputValues = new ArrayList<>(outputSchema.getFieldCount()); + selectIntoList(inputSchema, input, outputValues, fieldAccessDescriptor); + return Row.attachValues(outputSchema, outputValues); + } + + static Row rewrapRow(Row input, Schema outputSchema) { + if (input instanceof RowWithStorage) { + @Nullable Object @Nullable [] raw = ((RowWithStorage) input).getRawArray(); + if (raw != null) { + return Row.attachValues(outputSchema, raw); + } + return Row.attachValues(outputSchema, input.getValues()); + } + int n = outputSchema.getFieldCount(); + Object[] values = new Object[n]; + for (int i = 0; i < n; i++) { + values[i] = input.getValue(i); + } + return Row.attachValues(outputSchema, values); } - /** Select out of a given {@link Row} object. */ - private static void selectIntoRow( + /** Select out of a given {@link Row} object into an output value list. */ + private static void selectIntoList( Schema inputSchema, - Row input, - Row.Builder output, + @Nullable Row input, + List output, FieldAccessDescriptor fieldAccessDescriptor) { if (fieldAccessDescriptor.getAllFields()) { - List values = - (input != null) - ? input.getValues() - : Collections.nCopies(inputSchema.getFieldCount(), null); - output.addValues(values); + if (input == null) { + for (int i = 0; i < inputSchema.getFieldCount(); i++) { + output.add(null); + } + } else if (input instanceof RowWithGetters) { + int count = inputSchema.getFieldCount(); + for (int i = 0; i < count; i++) { + output.add(input.getValue(i)); + } + } else { + output.addAll(input.getValues()); + } return; } for (int fieldId : fieldAccessDescriptor.fieldIdsAccessed()) { - // TODO: Once we support specific qualifiers (like array slices), extract them here. - output.addValue((input != null) ? input.getValue(fieldId) : null); + output.add((input != null) ? input.getValue(fieldId) : null); } - Schema outputSchema = output.getSchema(); for (Map.Entry nested : fieldAccessDescriptor.getNestedFieldsAccessed().entrySet()) { FieldDescriptor field = nested.getKey(); FieldAccessDescriptor nestedAccess = nested.getValue(); FieldType nestedInputType = inputSchema.getField(field.getFieldId()).getType(); - FieldType nestedOutputType = outputSchema.getField(output.nextFieldId()).getType(); - selectIntoRowWithQualifiers( + selectIntoListWithQualifiers( field.getQualifiers(), 0, - input.getValue(field.getFieldId()), + (input != null) ? input.getValue(field.getFieldId()) : null, output, nestedAccess, - nestedInputType, - nestedOutputType); + nestedInputType); } } - private static void selectIntoRowWithQualifiers( + static int countFields( + FieldType inputType, List qualifiers, int qualifierPosition, - Object value, - Row.Builder output, + FieldAccessDescriptor descriptor) { + FieldType type = inputType; + for (int i = qualifierPosition; i < qualifiers.size(); i++) { + Qualifier q = qualifiers.get(i); + switch (q.getKind()) { + case LIST: + type = checkNotNull(type.getCollectionElementType()); + break; + case MAP: + type = checkNotNull(type.getMapValueType()); + break; + default: + throw new RuntimeException("Unexpected type " + q.getKind()); + } + } + return countRowFields(checkNotNull(type.getRowSchema()), descriptor); + } + + static int countRowFields(Schema schema, FieldAccessDescriptor descriptor) { + if (descriptor.getAllFields()) { + return schema.getFieldCount(); + } + int count = descriptor.getFieldsAccessed().size(); + for (Map.Entry nested : + descriptor.getNestedFieldsAccessed().entrySet()) { + FieldDescriptor fd = nested.getKey(); + FieldType type = schema.getField(fd.getFieldId()).getType(); + count += countFields(type, fd.getQualifiers(), 0, nested.getValue()); + } + return count; + } + + private static void selectIntoListWithQualifiers( + List qualifiers, + int qualifierPosition, + @Nullable Object value, + List output, FieldAccessDescriptor fieldAccessDescriptor, - FieldType inputType, - FieldType outputType) { + FieldType inputType) { if (qualifierPosition >= qualifiers.size()) { // We have already constructed all arrays and maps. What remains must be a Row. - Row row = (Row) value; - selectIntoRow(inputType.getRowSchema(), row, output, fieldAccessDescriptor); + selectIntoList(inputType.getRowSchema(), (Row) value, output, fieldAccessDescriptor); return; } @@ -313,98 +414,75 @@ private static void selectIntoRowWithQualifiers( case LIST: { FieldType nestedInputType = checkNotNull(inputType.getCollectionElementType()); - FieldType nestedOutputType = checkNotNull(outputType.getCollectionElementType()); Iterable iterable = (Iterable) value; + int nestedFieldCount = + countFields( + nestedInputType, qualifiers, qualifierPosition + 1, fieldAccessDescriptor); - // When selecting multiple subelements under a list, we distribute the select - // resulting in multiple lists. For example, if there is a field "list" with type - // {a: string, b: int}[], selecting list.a, list.b results in a schema of type - // {a: string[], b: int[]}. This preserves the invariant that the name selected always - // appears in the top-level schema. - Schema tempSchema = Schema.builder().addField("a", nestedInputType).build(); - FieldAccessDescriptor tempAccessDescriptor = - FieldAccessDescriptor.create() - .withNestedField("a", fieldAccessDescriptor) - .resolve(tempSchema); - Schema nestedSchema = getOutputSchema(tempSchema, tempAccessDescriptor); - - List> selectedLists = - Lists.newArrayListWithCapacity(nestedSchema.getFieldCount()); - for (int i = 0; i < nestedSchema.getFieldCount(); i++) { - if (iterable == null) { - selectedLists.add(null); - } else { - selectedLists.add(Lists.newArrayListWithCapacity(Iterables.size(iterable))); + if (iterable == null) { + for (int i = 0; i < nestedFieldCount; i++) { + output.add(null); } + break; } - if (iterable != null) { - for (Object o : iterable) { - Row.Builder selectElementBuilder = Row.withSchema(nestedSchema); - selectIntoRowWithQualifiers( - qualifiers, - qualifierPosition + 1, - o, - selectElementBuilder, - fieldAccessDescriptor, - nestedInputType, - nestedOutputType); - - Row elementBeforeDistribution = selectElementBuilder.build(); - for (int i = 0; i < nestedSchema.getFieldCount(); ++i) { - selectedLists.get(i).add(elementBeforeDistribution.getValue(i)); - } - } + int initialCapacity = + iterable instanceof Collection + ? ((Collection) iterable).size() + : Iterables.size(iterable); + List> selectedLists = Lists.newArrayListWithCapacity(nestedFieldCount); + for (int i = 0; i < nestedFieldCount; i++) { + selectedLists.add(new ArrayList<>(initialCapacity)); } - for (List aList : selectedLists) { - output.addValue(aList); + List scratch = new ArrayList<>(nestedFieldCount); + for (Object o : iterable) { + scratch.clear(); + selectIntoListWithQualifiers( + qualifiers, + qualifierPosition + 1, + o, + scratch, + fieldAccessDescriptor, + nestedInputType); + for (int i = 0; i < nestedFieldCount; ++i) { + selectedLists.get(i).add(scratch.get(i)); + } } + output.addAll(selectedLists); break; } case MAP: { FieldType nestedInputType = checkNotNull(inputType.getMapValueType()); - FieldType nestedOutputType = checkNotNull(outputType.getMapValueType()); - - // When selecting multiple subelements under a map, we distribute the select - // resulting in multiple maps. The semantics are the same as for lists above (except we - // only support subelement select for map values, not for map keys). - Schema tempSchema = Schema.builder().addField("a", nestedInputType).build(); - FieldAccessDescriptor tempAccessDescriptor = - FieldAccessDescriptor.create() - .withNestedField("a", fieldAccessDescriptor) - .resolve(tempSchema); - Schema nestedSchema = getOutputSchema(tempSchema, tempAccessDescriptor); - List selectedMaps = Lists.newArrayListWithExpectedSize(nestedSchema.getFieldCount()); - for (int i = 0; i < nestedSchema.getFieldCount(); ++i) { - if (value == null) { - selectedMaps.add(null); - } else { - selectedMaps.add(Maps.newHashMap()); - } - } + int nestedFieldCount = + countFields( + nestedInputType, qualifiers, qualifierPosition + 1, fieldAccessDescriptor); - if (value != null) { - Map map = (Map) value; - for (Map.Entry entry : map.entrySet()) { - Row.Builder selectValueBuilder = Row.withSchema(nestedSchema); - selectIntoRowWithQualifiers( - qualifiers, - qualifierPosition + 1, - entry.getValue(), - selectValueBuilder, - fieldAccessDescriptor, - nestedInputType, - nestedOutputType); - - Row valueBeforeDistribution = selectValueBuilder.build(); - for (int i = 0; i < nestedSchema.getFieldCount(); ++i) { - selectedMaps.get(i).put(entry.getKey(), valueBeforeDistribution.getValue(i)); - } + if (value == null) { + for (int i = 0; i < nestedFieldCount; i++) { + output.add(null); } + break; } - for (Map aMap : selectedMaps) { - output.addValue(aMap); + Map map = (Map) value; + List> selectedMaps = Lists.newArrayListWithCapacity(nestedFieldCount); + for (int i = 0; i < nestedFieldCount; ++i) { + selectedMaps.add(Maps.newHashMapWithExpectedSize(map.size())); + } + List scratch = new ArrayList<>(nestedFieldCount); + for (Map.Entry entry : map.entrySet()) { + scratch.clear(); + selectIntoListWithQualifiers( + qualifiers, + qualifierPosition + 1, + entry.getValue(), + scratch, + fieldAccessDescriptor, + nestedInputType); + for (int i = 0; i < nestedFieldCount; ++i) { + selectedMaps.get(i).put(entry.getKey(), scratch.get(i)); + } } + output.addAll(selectedMaps); break; } default: From 1bd9fb5af58c82fccfd4b27ac1ad58ec48e2120b Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:56:21 -0800 Subject: [PATCH 08/15] Optimize Group, SchemaAggregateFn, and CombineFns Fixes major aggregation allocation and combiner-lifting bugs: - SchemaAggregateFn: fixes needsFlattening check (comparing inputSubSchema instead of inputSchema), extracts single-field inputs directly without allocating throwaway Rows, adds compact(Object[]) override, and uses Row.attachValues for outputs. - Group: preserves fewKeys=true in withHotKeyFanout so streaming combiner lifting remains enabled. - CombineFns: eliminates eager string concatenation and unnecessary allocations in CoCombineResult and mergeAccumulators. --- .../beam/sdk/schemas/transforms/Group.java | 17 +- .../schemas/transforms/SchemaAggregateFn.java | 527 +++++++++++++++--- .../beam/sdk/transforms/CombineFns.java | 24 +- .../sdk/schemas/transforms/GroupTest.java | 78 +++ 4 files changed, 562 insertions(+), 84 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Group.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Group.java index 8d314430b9c9..b5e7c8cea618 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Group.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Group.java @@ -44,7 +44,6 @@ import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptors; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.checkerframework.checker.nullness.qual.Nullable; /** @@ -957,9 +956,7 @@ public PCollection expand(PCollection input) { new DoFn>, Row>() { @ProcessElement public void process(@Element KV> e, OutputReceiver o) { - o.output( - Row.withSchema(outputSchema) - .attachValues(Lists.newArrayList(e.getKey(), e.getValue()))); + o.output(Row.attachValues(outputSchema, e.getKey(), e.getValue())); } })) .setRowSchema(outputSchema); @@ -1274,18 +1271,20 @@ public CombineFieldsByFields agg PTransform>, PCollection>> getCombineTransform( Schema schema) { SchemaAggregateFn.Inner fn = getSchemaAggregateFn().withSchema(schema); + Combine.PerKey combine = + getFewKeys() ? Combine.fewKeys(fn) : Combine.perKey(fn); @Nullable Fanout fanout = getFanout(); if (fanout != null) { switch (fanout.getKind()) { case NUMBER: - return Combine.perKey(fn).withHotKeyFanout(fanout.getNumber()); + return combine.withHotKeyFanout(fanout.getNumber()); case FUNCTION: - return Combine.perKey(fn).withHotKeyFanout(fanout.getFunction()); + return combine.withHotKeyFanout(fanout.getFunction()); default: throw new RuntimeException("Unexpected kind: " + fanout.getKind()); } } - return getFewKeys() ? Combine.fewKeys(fn) : Combine.perKey(fn); + return combine; } @Override @@ -1308,9 +1307,7 @@ public PCollection expand(PCollection input) { @ProcessElement public void process(@Element KV element, OutputReceiver o) { o.output( - Row.withSchema(outputSchema) - .attachValues( - Lists.newArrayList(element.getKey(), element.getValue()))); + Row.attachValues(outputSchema, element.getKey(), element.getValue())); } })) .setRowSchema(outputSchema); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/SchemaAggregateFn.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/SchemaAggregateFn.java index f37f92ff2e43..8a017024ede4 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/SchemaAggregateFn.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/SchemaAggregateFn.java @@ -19,23 +19,30 @@ import com.google.auto.value.AutoValue; import java.io.Serializable; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import org.apache.beam.sdk.coders.CannotProvideCoderException; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.CoderRegistry; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; +import org.apache.beam.sdk.schemas.FieldAccessDescriptor.FieldDescriptor; import org.apache.beam.sdk.schemas.FieldTypeDescriptors; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.Field; import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.Schema.LogicalType; +import org.apache.beam.sdk.schemas.Schema.TypeName; import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.schemas.utils.RowSelector; import org.apache.beam.sdk.schemas.utils.SelectHelpers; -import org.apache.beam.sdk.schemas.utils.SelectHelpers.RowSelectorContainer; import org.apache.beam.sdk.transforms.Combine.CombineFn; import org.apache.beam.sdk.transforms.CombineFns; -import org.apache.beam.sdk.transforms.CombineFns.CoCombineResult; import org.apache.beam.sdk.transforms.CombineFns.ComposedCombineFn; import org.apache.beam.sdk.transforms.SimpleFunction; import org.apache.beam.sdk.values.Row; @@ -43,11 +50,14 @@ import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Instant; +import org.joda.time.ReadableInstant; /** This is the builder used by {@link Group} to build up a composed {@link CombineFn}. */ @SuppressWarnings({ "nullness", // TODO(https://github.com/apache/beam/issues/20497) - "rawtypes" + "rawtypes", + "unchecked" }) class SchemaAggregateFn { static Inner create() { @@ -56,11 +66,318 @@ static Inner create() { .build(); } + /** + * Attempts to resolve {@code descriptor} to a direct field-index chain (with no intervening + * array/map qualifiers or nested row flattening). Returns {@code null} when a general {@link + * RowSelector} must be used. + */ + private static int @Nullable [] tryResolveDirectPath( + Schema inputSchema, FieldAccessDescriptor descriptor) { + int[] buf = new int[4]; + int depth = 0; + Schema curSchema = inputSchema; + FieldAccessDescriptor cur = descriptor; + while (true) { + if (cur.getAllFields()) { + return null; + } + List direct = cur.getFieldsAccessed(); + Map nested = cur.getNestedFieldsAccessed(); + if (direct.size() == 1 && nested.isEmpty()) { + FieldDescriptor fd = direct.get(0); + Integer id = fd.getFieldId(); + if (id == null || !fd.getQualifiers().isEmpty()) { + return null; + } + FieldType leafType = curSchema.getField(id).getType(); + // For nested ROW leaves, SelectHelpers flattening could unpack its child field. + if (leafType.getTypeName() == TypeName.ROW) { + return null; + } + if (depth == buf.length) { + buf = Arrays.copyOf(buf, depth * 2); + } + buf[depth++] = id; + return Arrays.copyOf(buf, depth); + } + if (direct.isEmpty() && nested.size() == 1) { + Map.Entry entry = + nested.entrySet().iterator().next(); + FieldDescriptor fd = entry.getKey(); + Integer id = fd.getFieldId(); + if (id == null || !fd.getQualifiers().isEmpty()) { + return null; + } + FieldType nodeType = curSchema.getField(id).getType(); + if (nodeType.getTypeName() != TypeName.ROW) { + return null; + } + if (depth == buf.length) { + buf = Arrays.copyOf(buf, depth * 2); + } + buf[depth++] = id; + curSchema = nodeType.getRowSchema(); + cur = entry.getValue(); + } else { + return null; + } + } + } + + private static @Nullable LogicalType[] buildLogicalUnwrapChain( + FieldType fieldType) { + if (!fieldType.getTypeName().isLogicalType()) { + return null; + } + List> chain = new ArrayList<>(2); + FieldType cur = fieldType; + while (cur.getTypeName().isLogicalType()) { + LogicalType lt = (LogicalType) cur.getLogicalType(); + chain.add(lt); + cur = lt.getBaseType(); + } + return chain.toArray(new LogicalType[0]); + } + + private static @Nullable Object applyUnwrapChain( + @Nullable Object value, LogicalType @Nullable [] chain) { + if (value == null || chain == null) { + return value; + } + Object cur = value; + for (int i = 0; i < chain.length; i++) { + cur = chain[i].toBaseType(cur); + if (cur == null) { + return null; + } + } + return cur; + } + /** Implementation of {@link #create}. */ @AutoValue @AutoValue.CopyAnnotations @SuppressWarnings("rawtypes") abstract static class Inner extends CombineFn { + private static final byte OUT_DIRECT = 0; + private static final byte OUT_ARRAY = 1; + private static final byte OUT_DATETIME = 2; + private static final byte OUT_BYTES = 3; + + // Transient execution plan derived from fieldAggregations/inputSchema/outputSchema to eliminate + // per-row/per-key allocation and double-hashing inside CombineFns.CoCombineResult. + private transient volatile @Nullable ExecutionPlan plan; + + private static final class ExecutionPlan { + final int count; + final CombineFn[] combineFns; + final FieldExtractor[] extractors; + // Non-negative if extract[i] can reuse a previously extracted value computed at slot < i. + final int[] reuseSlot; + final boolean hasReuse; + final byte[] outputCoercions; + final boolean useFullRowBuilder; + final boolean[] outputNullable; + final boolean[] outputArrayElemNonNull; + final Schema outputSchema; + + ExecutionPlan(Schema inputSchema, Schema outputSchema, List aggregations) { + int n = aggregations.size(); + this.count = n; + this.combineFns = new CombineFn[n]; + this.extractors = new FieldExtractor[n]; + this.reuseSlot = new int[n]; + Arrays.fill(this.reuseSlot, -1); + this.outputCoercions = new byte[n]; + this.outputNullable = new boolean[n]; + this.outputArrayElemNonNull = new boolean[n]; + this.outputSchema = outputSchema; + + boolean anyReuse = false; + boolean fullBuilder = false; + Map seenExtractors = new HashMap<>(n * 2); + + for (int i = 0; i < n; i++) { + FieldAggregation agg = aggregations.get(i); + combineFns[i] = agg.fn; + extractors[i] = buildExtractor(inputSchema, agg); + + Object extKey = + new java.util.AbstractMap.SimpleImmutableEntry<>( + agg.fieldsToAggregate, agg.aggregateBaseValues); + Integer prev = seenExtractors.get(extKey); + if (prev != null) { + reuseSlot[i] = prev; + anyReuse = true; + } else { + seenExtractors.put(extKey, i); + } + + FieldType outType = outputSchema.getField(i).getType(); + outputNullable[i] = outType.getNullable(); + switch (outType.getTypeName()) { + case BYTE: + case INT16: + case INT32: + case INT64: + case FLOAT: + case DOUBLE: + case BOOLEAN: + case STRING: + case DECIMAL: + case ROW: + outputCoercions[i] = OUT_DIRECT; + break; + case DATETIME: + outputCoercions[i] = OUT_DATETIME; + break; + case BYTES: + outputCoercions[i] = OUT_BYTES; + break; + case ARRAY: + FieldType elemType = outType.getCollectionElementType(); + if (elemType == null + || elemType.getTypeName() == TypeName.DATETIME + || elemType.getTypeName() == TypeName.BYTES + || elemType.getTypeName() == TypeName.ROW + || elemType.getTypeName() == TypeName.LOGICAL_TYPE + || elemType.getTypeName().isCollectionType() + || elemType.getTypeName() == TypeName.MAP) { + fullBuilder = true; + } else { + outputArrayElemNonNull[i] = !elemType.getNullable(); + } + outputCoercions[i] = OUT_ARRAY; + break; + case ITERABLE: + case LOGICAL_TYPE: + case MAP: + default: + // Delegate validation/coercion of logical types, iterables, and maps to Row.Builder. + fullBuilder = true; + outputCoercions[i] = OUT_DIRECT; + break; + } + } + this.hasReuse = anyReuse; + this.useFullRowBuilder = fullBuilder; + } + + private static FieldExtractor buildExtractor(Schema inputSchema, FieldAggregation agg) { + if (agg.fieldsToAggregate.referencesSingleField()) { + if (!agg.needsFlattening) { + int @Nullable [] directPath = tryResolveDirectPath(inputSchema, agg.fieldsToAggregate); + if (directPath != null) { + LogicalType @Nullable [] unwrapChain = null; + if (agg.aggregateBaseValues) { + FieldType leafType = agg.flattenedInputSubSchema.getField(0).getType(); + unwrapChain = buildLogicalUnwrapChain(leafType); + } + if (directPath.length == 1 && unwrapChain == null) { + return new DirectTopLevelExtractor(directPath[0]); + } + return new DirectPathExtractor(directPath, unwrapChain); + } + } + return new SelectorSingleExtractor(inputSchema, agg); + } + return new SelectorMultiExtractor(inputSchema, agg); + } + } + + private interface FieldExtractor { + @Nullable Object extract(Row row); + } + + private static final class DirectTopLevelExtractor implements FieldExtractor { + private final int fieldIdx; + + DirectTopLevelExtractor(int fieldIdx) { + this.fieldIdx = fieldIdx; + } + + @Override + public @Nullable Object extract(Row row) { + return row.getValue(fieldIdx); + } + } + + private static final class DirectPathExtractor implements FieldExtractor { + private final int[] path; + private final LogicalType @Nullable [] unwrapChain; + + DirectPathExtractor(int[] path, LogicalType @Nullable [] unwrapChain) { + this.path = path; + this.unwrapChain = unwrapChain; + } + + @Override + public @Nullable Object extract(Row row) { + Row cur = row; + int last = path.length - 1; + for (int i = 0; i < last; i++) { + cur = cur.getRow(path[i]); + if (cur == null) { + return null; + } + } + Object val = cur.getValue(path[last]); + return applyUnwrapChain(val, unwrapChain); + } + } + + private static final class SelectorSingleExtractor implements FieldExtractor { + private final RowSelector rowSelector; + private final @Nullable RowSelector flatteningSelector; + private final LogicalType @Nullable [] unwrapChain; + + SelectorSingleExtractor(Schema inputSchema, FieldAggregation agg) { + this.rowSelector = + SelectHelpers.getRowSelectorOptimized(inputSchema, agg.fieldsToAggregate); + this.flatteningSelector = + agg.needsFlattening + ? SelectHelpers.getRowSelectorOptimized( + agg.inputSubSchema, agg.flattenedFieldAccessDescriptor) + : null; + this.unwrapChain = + agg.aggregateBaseValues + ? buildLogicalUnwrapChain(agg.flattenedInputSubSchema.getField(0).getType()) + : null; + } + + @Override + public @Nullable Object extract(Row row) { + Row selected = rowSelector.select(row); + if (flatteningSelector != null) { + selected = flatteningSelector.select(selected); + } + return applyUnwrapChain(selected.getValue(0), unwrapChain); + } + } + + private static final class SelectorMultiExtractor implements FieldExtractor { + private final RowSelector rowSelector; + + SelectorMultiExtractor(Schema inputSchema, FieldAggregation agg) { + this.rowSelector = + SelectHelpers.getRowSelectorOptimized(inputSchema, agg.fieldsToAggregate); + } + + @Override + public Row extract(Row row) { + return rowSelector.select(row); + } + } + + private ExecutionPlan getPlan() { + ExecutionPlan p = this.plan; + if (p == null) { + p = new ExecutionPlan(getInputSchema(), getOutputSchema(), getFieldAggregations()); + this.plan = p; + } + return p; + } + // Represents an aggregation of one or more fields. static class FieldAggregation implements Serializable { FieldAccessDescriptor fieldsToAggregate; @@ -115,7 +432,7 @@ static class FieldAggregation implements Serializable { SelectHelpers.allLeavesDescriptor(inputSubSchema, SelectHelpers.CONCAT_FIELD_NAMES); this.flattenedInputSubSchema = SelectHelpers.getOutputSchema(inputSubSchema, flattenedFieldAccessDescriptor); - this.needsFlattening = !inputSchema.equals(flattenedInputSubSchema); + this.needsFlattening = !this.inputSubSchema.equals(flattenedInputSubSchema); } else { this.fieldsToAggregate = fieldsToAggregate; this.inputSubSchema = null; @@ -176,15 +493,13 @@ Inner withSchema(Schema inputSchema) { .collect(Collectors.toList()); ComposedCombineFn composedCombineFn = null; + // ComposedCombineFn is retained solely to provide wire-compatible KeyedAccumulatorCoder; + // runtime extraction executes through ExecutionPlan. + SimpleFunction coderPlaceholderFn = CoderPlaceholderExtractFn.INSTANCE; for (int i = 0; i < fieldAggregations.size(); ++i) { FieldAggregation fieldAggregation = fieldAggregations.get(i); - SimpleFunction extractFunction; Coder extractOutputCoder; if (fieldAggregation.fieldsToAggregate.referencesSingleField()) { - extractFunction = - new ExtractSingleFieldFunction( - inputSchema, fieldAggregation.aggregateBaseValues, fieldAggregation); - FieldType fieldType = fieldAggregation.flattenedInputSubSchema.getField(0).getType(); if (fieldAggregation.aggregateBaseValues) { while (fieldType.getTypeName().isLogicalType()) { @@ -193,14 +508,13 @@ Inner withSchema(Schema inputSchema) { } extractOutputCoder = SchemaCoder.coderForFieldType(fieldType); } else { - extractFunction = new ExtractFieldsFunction(inputSchema, fieldAggregation); extractOutputCoder = SchemaCoder.of(fieldAggregation.inputSubSchema); } if (i == 0) { composedCombineFn = CombineFns.compose() .with( - extractFunction, + coderPlaceholderFn, extractOutputCoder, fieldAggregation.fn, fieldAggregation.combineTag); @@ -208,7 +522,7 @@ Inner withSchema(Schema inputSchema) { composedCombineFn = ((ComposedCombineFn) composedCombineFn) .with( - extractFunction, + coderPlaceholderFn, extractOutputCoder, fieldAggregation.fn, fieldAggregation.combineTag); @@ -241,7 +555,8 @@ Inner aggregateFields( boolean aggregateBaseValues, CombineFn fn, Field outputField) { - List fieldAggregations = getFieldAggregations(); + // Copy before mutating to keep AutoValue instances immutable when reused by callers. + List fieldAggregations = new ArrayList<>(getFieldAggregations()); TupleTag combineTag = new TupleTag<>(Integer.toString(fieldAggregations.size())); FieldAggregation fieldAggregation = new FieldAggregation<>( @@ -262,70 +577,105 @@ private Schema getOutputSchema(List fieldAggregations) { return outputSchema.build(); } - /** Extract a single field from an input {@link Row}. */ - private static class ExtractSingleFieldFunction extends SimpleFunction { - private final RowSelector rowSelector; - private final boolean extractBaseValue; - private final @Nullable RowSelector flatteningSelector; - private final FieldAggregation fieldAggregation; - - private ExtractSingleFieldFunction( - Schema inputSchema, boolean extractBaseValue, FieldAggregation fieldAggregation) { - rowSelector = - new RowSelectorContainer(inputSchema, fieldAggregation.fieldsToAggregate, true); - this.extractBaseValue = extractBaseValue; - flatteningSelector = - fieldAggregation.needsFlattening - ? new RowSelectorContainer( - fieldAggregation.inputSubSchema, - fieldAggregation.flattenedFieldAccessDescriptor, - true) - : null; - this.fieldAggregation = fieldAggregation; - } + /** Placeholder extract function used solely when constructing ComposedCombineFn's coder. */ + private static final class CoderPlaceholderExtractFn extends SimpleFunction { + static final CoderPlaceholderExtractFn INSTANCE = new CoderPlaceholderExtractFn(); @Override - public OutputT apply(Row row) { - Row selected = rowSelector.select(row); - if (fieldAggregation.needsFlattening) { - selected = flatteningSelector.select(selected); - } - if (extractBaseValue - && selected.getSchema().getField(0).getType().getTypeName().isLogicalType()) { - return (OutputT) selected.getBaseValue(0, Object.class); - } - return selected.getValue(0); + public Object apply(Row input) { + throw new UnsupportedOperationException("Executed via SchemaAggregateFn.ExecutionPlan"); } } - /** Extract multiple fields from an input {@link Row}. */ - private static class ExtractFieldsFunction extends SimpleFunction { - private final RowSelector rowSelector; - - private ExtractFieldsFunction(Schema inputSchema, FieldAggregation fieldAggregation) { - rowSelector = - new RowSelectorContainer(inputSchema, fieldAggregation.fieldsToAggregate, true); + @Override + public Object[] createAccumulator() { + ExecutionPlan p = getPlan(); + Object[] acc = new Object[p.count]; + CombineFn[] fns = p.combineFns; + for (int i = 0; i < fns.length; i++) { + acc[i] = fns[i].createAccumulator(); } + return acc; + } - @Override - public Row apply(Row row) { - return rowSelector.select(row); + @Override + public Object[] addInput(Object[] accumulator, Row input) { + ExecutionPlan p = getPlan(); + CombineFn[] fns = p.combineFns; + FieldExtractor[] exts = p.extractors; + int n = p.count; + if (!p.hasReuse) { + for (int i = 0; i < n; i++) { + accumulator[i] = fns[i].addInput(accumulator[i], exts[i].extract(input)); + } + } else { + Object[] extracted = new Object[n]; + int[] reuse = p.reuseSlot; + for (int i = 0; i < n; i++) { + int slot = reuse[i]; + Object val; + if (slot >= 0) { + val = extracted[slot]; + } else { + val = exts[i].extract(input); + extracted[i] = val; + } + accumulator[i] = fns[i].addInput(accumulator[i], val); + } } + return accumulator; } @Override - public Object[] createAccumulator() { - return getComposedCombineFn().createAccumulator(); + public Object[] compact(Object[] accumulator) { + ExecutionPlan p = getPlan(); + CombineFn[] fns = p.combineFns; + for (int i = 0; i < fns.length; i++) { + accumulator[i] = fns[i].compact(accumulator[i]); + } + return accumulator; } @Override - public Object[] addInput(Object[] accumulator, Row input) { - return getComposedCombineFn().addInput(accumulator, input); + public Object[] mergeAccumulators(Iterable accumulators) { + ExecutionPlan p = getPlan(); + CombineFn[] fns = p.combineFns; + Iterator iter = accumulators.iterator(); + if (!iter.hasNext()) { + return createAccumulator(); + } + Object[] merged = new Object[fns.length]; + for (int i = 0; i < fns.length; i++) { + merged[i] = fns[i].mergeAccumulators(new SlotIterable(accumulators, i)); + } + return merged; } - @Override - public Object[] mergeAccumulators(Iterable accumulator) { - return getComposedCombineFn().mergeAccumulators(accumulator); + private static final class SlotIterable implements Iterable { + private final Iterable source; + private final int index; + + SlotIterable(Iterable source, int index) { + this.source = source; + this.index = index; + } + + @Override + public Iterator iterator() { + final Iterator it = source.iterator(); + final int idx = index; + return new Iterator() { + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public Object next() { + return it.next()[idx]; + } + }; + } } @Override @@ -341,14 +691,55 @@ public Coder getDefaultOutputCoder(CoderRegistry registry, Coder input @Override public Row extractOutput(Object[] accumulator) { - // Build a row containing a field for every aggregate that was registered. - CoCombineResult coCombineResult = getComposedCombineFn().extractOutput(accumulator); - Row.Builder output = Row.withSchema(getOutputSchema()); - for (FieldAggregation fieldAggregation : getFieldAggregations()) { - Object aggregate = coCombineResult.get(fieldAggregation.combineTag); - output.addValue(aggregate); + ExecutionPlan p = getPlan(); + CombineFn[] fns = p.combineFns; + int n = p.count; + if (p.useFullRowBuilder) { + Row.Builder output = Row.withSchema(p.outputSchema); + for (int i = 0; i < n; i++) { + output.addValue(fns[i].extractOutput(accumulator[i])); + } + return output.build(); + } + Object[] outValues = new Object[n]; + byte[] coercions = p.outputCoercions; + boolean[] nullable = p.outputNullable; + boolean[] arrayElemNonNull = p.outputArrayElemNonNull; + for (int i = 0; i < n; i++) { + Object val = fns[i].extractOutput(accumulator[i]); + if (val == null) { + if (!nullable[i]) { + throw new IllegalArgumentException( + String.format("Field %s is not nullable", p.outputSchema.getField(i).getName())); + } + continue; + } + byte mode = coercions[i]; + if (mode == OUT_ARRAY) { + List list = + val instanceof List ? (List) val : Lists.newArrayList((Iterable) val); + if (arrayElemNonNull[i]) { + for (int j = 0, m = list.size(); j < m; j++) { + if (list.get(j) == null) { + throw new IllegalArgumentException( + String.format( + "Array field %s does not allow null elements", + p.outputSchema.getField(i).getName())); + } + } + } + val = list; + } else if (mode == OUT_DATETIME && !(val instanceof Instant)) { + val = ((ReadableInstant) val).toInstant(); + } else if (mode == OUT_BYTES && val instanceof ByteBuffer) { + ByteBuffer bb = ((ByteBuffer) val).slice(); + byte[] bytes = new byte[bb.remaining()]; + bb.get(bytes); + val = bytes; + } + outValues[i] = val; } - return output.build(); + return Row.attachValues(p.outputSchema, outValues); } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/CombineFns.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/CombineFns.java index 404d199078f0..35ba21195100 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/CombineFns.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/CombineFns.java @@ -180,7 +180,8 @@ private enum NullValue { * @throws NullPointerException if any key or value in {@code valuesMap} is null */ CoCombineResult(Map, Object> valuesMap) { - ImmutableMap.Builder, Object> builder = ImmutableMap.builder(); + ImmutableMap.Builder, Object> builder = + ImmutableMap.builderWithExpectedSize(valuesMap.size()); for (Entry, Object> entry : valuesMap.entrySet()) { if (entry.getValue() != null) { builder.put(entry); @@ -191,6 +192,14 @@ private enum NullValue { this.valuesMap = builder.build(); } + private CoCombineResult(ImmutableMap, Object> valuesMap) { + this.valuesMap = valuesMap; + } + + static Object sentinelForNull(@Nullable Object value) { + return value != null ? value : NullValue.INSTANCE; + } + /** * Returns the value represented by the given {@link TupleTag}. * @@ -198,9 +207,10 @@ private enum NullValue { */ @SuppressWarnings("unchecked") public @Nullable V get(TupleTag tag) { - checkArgument( - valuesMap.keySet().contains(tag), "TupleTag " + tag + " is not in the CoCombineResult"); Object value = valuesMap.get(tag); + if (value == null) { + throw new IllegalArgumentException("TupleTag " + tag + " is not in the CoCombineResult"); + } if (value == NullValue.INSTANCE) { return null; } else { @@ -403,11 +413,13 @@ public Object[] mergeAccumulators(Iterable accumulators) { @Override public CoCombineResult extractOutput(Object[] accumulator) { - Map, Object> valuesMap = Maps.newHashMap(); + ImmutableMap.Builder, Object> builder = + ImmutableMap.builderWithExpectedSize(combineFnCount); for (int i = 0; i < combineFnCount; ++i) { - valuesMap.put(outputTags.get(i), combineFns.get(i).extractOutput(accumulator[i])); + Object value = combineFns.get(i).extractOutput(accumulator[i]); + builder.put(outputTags.get(i), CoCombineResult.sentinelForNull(value)); } - return new CoCombineResult(valuesMap); + return new CoCombineResult(builder.build()); } @Override diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/GroupTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/GroupTest.java index 9ecaafbff27f..a829cf71d175 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/GroupTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/GroupTest.java @@ -671,6 +671,84 @@ public void process(@Element Row value) { pipeline.run(); } + @Test + @Category(NeedsRunner.class) + public void testAggregateSingleFieldNestedArrayQualifier() { + Schema itemSchema = Schema.builder().addInt64Field("v").build(); + Schema inputSchema = + Schema.builder() + .addStringField("k") + .addArrayField("items", FieldType.row(itemSchema)) + .build(); + + Row r1 = + Row.withSchema(inputSchema) + .addValues( + "g1", + java.util.Arrays.asList( + Row.withSchema(itemSchema).addValues(10L).build(), + Row.withSchema(itemSchema).addValues(20L).build())) + .build(); + Row r2 = + Row.withSchema(inputSchema) + .addValues( + "g1", + java.util.Collections.singletonList( + Row.withSchema(itemSchema).addValues(30L).build())) + .build(); + + org.apache.beam.sdk.transforms.Combine.CombineFn, Long, Long> sumLists = + new org.apache.beam.sdk.transforms.Combine.CombineFn, Long, Long>() { + @Override + public Long createAccumulator() { + return 0L; + } + + @Override + public Long addInput(Long acc, List input) { + long sum = acc; + for (Long x : input) { + sum += x; + } + return sum; + } + + @Override + public Long mergeAccumulators(Iterable accs) { + long sum = 0L; + for (Long a : accs) { + sum += a; + } + return sum; + } + + @Override + public Long extractOutput(Long acc) { + return acc; + } + }; + + PCollection grouped = + pipeline + .apply(Create.of(r1, r2)) + .setRowSchema(inputSchema) + .apply(Group.byFieldNames("k").aggregateField("items.v", sumLists, "total")); + + Schema keySchema = Schema.builder().addStringField("k").build(); + Schema valSchema = Schema.builder().addInt64Field("total").build(); + Schema outSchema = + Schema.builder().addRowField("key", keySchema).addRowField("value", valSchema).build(); + PAssert.that(grouped) + .containsInAnyOrder( + Row.withSchema(outSchema) + .addValues( + Row.withSchema(keySchema).addValues("g1").build(), + Row.withSchema(valSchema).addValues(60L).build()) + .build()); + + pipeline.run(); + } + private static Void containsKIterableVs(List expectedKvs, Iterable actualKvs) { List> matchers = new ArrayList<>(); for (Row expected : expectedKvs) { From 852289c96b481a50119684eca78411fb788a1414 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:56:39 -0800 Subject: [PATCH 09/15] Optimize CoGroup with flat arrays, empty-side short-circuit, 2-way fast path, and fused broadcast joins Replaces per-key AutoValue/Map/TupleTag wrapper overhead with flat arrays, short-circuits inner joins when any required side is empty, adds a specialized 2-way join fast path, uses output-schema-aware RowSelectorContainer, and fuses broadcast join key extraction. --- .../beam/sdk/schemas/transforms/CoGroup.java | 497 ++++++++++++------ .../sdk/schemas/transforms/CoGroupTest.java | 40 ++ 2 files changed, 368 insertions(+), 169 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/CoGroup.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/CoGroup.java index 93381034e133..5ade8252c5db 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/CoGroup.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/CoGroup.java @@ -41,11 +41,11 @@ import org.apache.beam.sdk.transforms.DoFn.OutputReceiver; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.transforms.join.CoGbkResult; import org.apache.beam.sdk.transforms.join.CoGroupByKey; import org.apache.beam.sdk.transforms.join.KeyedPCollectionTuple; -import org.apache.beam.sdk.transforms.join.KeyedPCollectionTuple.TaggedKeyedPCollection; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionTuple; @@ -54,8 +54,6 @@ import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; import org.checkerframework.checker.nullness.qual.Nullable; @@ -207,11 +205,13 @@ "nullness" // TODO(https://github.com/apache/beam/issues/20497) }) public class CoGroup { - private static final List<@Nullable Row> NULL_LIST; + private static final List<@Nullable Row> NULL_LIST = Collections.singletonList(null); - static { - NULL_LIST = Lists.newArrayList(); - NULL_LIST.add(null); + private static boolean isEmpty(Iterable rows) { + if (rows instanceof Collection) { + return ((Collection) rows).isEmpty(); + } + return !rows.iterator().hasNext(); } /** @@ -337,6 +337,10 @@ static class JoinInformation implements Serializable { private final Map componentSchemas; private final List sortedTags; private final Map tagToKeyedTag; + private final Map> indexToTupleTag; + private final transient @Nullable PCollection singleMainInput; + private final @Nullable FieldAccessDescriptor singleMainKeyDescriptor; + private final int singleMainIndex; private JoinInformation( KeyedPCollectionTuple keyedPCollectionTuple, @@ -344,19 +348,28 @@ private JoinInformation( Schema keySchema, Map componentSchemas, List sortedTags, - Map tagToKeyedTag) { + Map tagToKeyedTag, + Map> indexToTupleTag, + @Nullable PCollection singleMainInput, + @Nullable FieldAccessDescriptor singleMainKeyDescriptor, + int singleMainIndex) { this.keyedPCollectionTuple = keyedPCollectionTuple; this.sideInputs = sideInputs; this.keySchema = keySchema; this.componentSchemas = componentSchemas; this.sortedTags = sortedTags; this.tagToKeyedTag = tagToKeyedTag; + this.indexToTupleTag = indexToTupleTag; + this.singleMainInput = singleMainInput; + this.singleMainKeyDescriptor = singleMainKeyDescriptor; + this.singleMainIndex = singleMainIndex; } private static JoinInformation from( PCollectionTuple input, Function getFieldAccessDescriptor, - Function getIsSideInput) { + Function getIsSideInput, + boolean deferSingleMainKeyExtraction) { KeyedPCollectionTuple keyedPCollectionTuple = KeyedPCollectionTuple.empty(input.getPipeline()); @@ -372,7 +385,10 @@ private static JoinInformation from( Map>>> sideInputs = Maps.newHashMap(); Map tagToKeyedTag = Maps.newHashMap(); + Map> indexToTupleTag = Maps.newHashMap(); Schema keySchema = null; + @Nullable Schema mainKeySchema = null; + int mainCount = 0; for (Map.Entry, PCollection> entry : input.getAll().entrySet()) { String tag = entry.getKey().getId(); PCollection pc = entry.getValue(); @@ -382,18 +398,36 @@ private static JoinInformation from( if (fieldAccessDescriptor == null) { throw new IllegalStateException("No fields were set for input " + tag); } + if (!getIsSideInput.apply(tag)) { + mainCount++; + } // Resolve the key schema, keeping the fields in the order specified by the user. // Otherwise, if different field names are specified for different PCollections, they // might not match up. // The key schema contains the field names from the first PCollection specified. FieldAccessDescriptor resolved = fieldAccessDescriptor.resolve(schema); Schema currentKeySchema = SelectHelpers.getOutputSchema(schema, resolved); + if (!getIsSideInput.apply(tag)) { + mainKeySchema = currentKeySchema; + } if (keySchema == null) { keySchema = currentKeySchema; } else { keySchema = SchemaUtils.mergeWideningNullable(keySchema, currentKeySchema); } } + // Only fuse single-main broadcast key extraction when nested composite key schemas match + // keySchema exactly (otherwise extractKey + SchemaCoder.of(keySchema) re-stamps nested + // schemas so Row.equals matches the broadcast multimap keys). + boolean fuseSingleMain = + deferSingleMainKeyExtraction + && mainCount == 1 + && keySchema != null + && mainKeySchema != null + && (!hasCompositeField(keySchema) || mainKeySchema.equals(keySchema)); + PCollection singleMainPc = null; + FieldAccessDescriptor singleMainDescriptor = null; + int singleMainIdx = -1; // Second loop so we can widen the keySchema with every input before using it for (Map.Entry, PCollection> entry : input.getAll().entrySet()) { String tag = entry.getKey().getId(); @@ -407,13 +441,21 @@ private static JoinInformation from( TupleTag randomTag = new TupleTag<>(); String keyedTag = tag + "_" + randomTag; tagToKeyedTag.put(tagIndex, keyedTag); - PCollection> keyedPCollection = - extractKey(pc, schema, keySchema, resolved, tag); if (getIsSideInput.apply(tag)) { + PCollection> keyedPCollection = + extractKey(pc, schema, keySchema, resolved, tag); sideInputs.put( keyedTag, keyedPCollection.apply("computeSideInputView" + tag, View.asMultimap())); + } else if (fuseSingleMain) { + singleMainPc = pc; + singleMainDescriptor = resolved; + singleMainIdx = tagIndex; } else { - keyedPCollectionTuple = keyedPCollectionTuple.and(keyedTag, keyedPCollection); + TupleTag rowTag = new TupleTag<>(keyedTag); + indexToTupleTag.put(tagIndex, rowTag); + PCollection> keyedPCollection = + extractKey(pc, schema, keySchema, resolved, tag); + keyedPCollectionTuple = keyedPCollectionTuple.and(rowTag, keyedPCollection); } } return new JoinInformation( @@ -422,7 +464,11 @@ private static JoinInformation from( keySchema, componentSchemas, sortedTags, - tagToKeyedTag); + tagToKeyedTag, + indexToTupleTag, + singleMainPc, + singleMainDescriptor, + singleMainIdx); } private static PCollection> extractKey( @@ -431,17 +477,33 @@ private static PCollection> extractKey( Schema keySchema, FieldAccessDescriptor keyFields, String tag) { + @Nullable SerializableFunction toRowFn = + SchemaUtils.isIdentityFunction(pCollection.getToRowFunction()) + ? null + : pCollection.getToRowFunction(); + RowSelectorContainer selectorContainer = + new RowSelectorContainer(schema, keyFields, keySchema, true); return pCollection .apply( "extractKey" + tag, ParDo.of( new DoFn>() { - private RowSelector rowSelector = - new RowSelectorContainer(schema, keyFields, true); + private transient @Nullable RowSelector rowSelector; + + @Setup + public void setup() { + this.rowSelector = selectorContainer.getOrCreateSelector(); + } @ProcessElement - public void process(@Element Row row, OutputReceiver> o) { - o.output(KV.of(rowSelector.select(row), row)); + public void process(@Element T element, OutputReceiver> o) { + RowSelector selector = this.rowSelector; + if (selector == null) { + selector = selectorContainer.getOrCreateSelector(); + this.rowSelector = selector; + } + Row row = toRowFn != null ? toRowFn.apply(element) : (Row) element; + o.output(KV.of(selector.select(row), row)); } })) .setCoder(KvCoder.of(SchemaCoder.of(keySchema), SchemaCoder.of(schema))); @@ -465,6 +527,20 @@ static void verify(PCollectionTuple input, JoinArguments joinArgs) { } } + private static boolean hasCompositeField(Schema schema) { + for (int i = 0; i < schema.getFieldCount(); i++) { + Schema.TypeName tn = schema.getField(i).getType().getTypeName(); + if (tn == Schema.TypeName.ROW + || tn == Schema.TypeName.ARRAY + || tn == Schema.TypeName.ITERABLE + || tn == Schema.TypeName.MAP) { + return true; + } + } + return false; + } + + /** Schema helpers for CoGroup output construction. */ @AutoValue public abstract static class Result { abstract Row getKey(); @@ -477,61 +553,6 @@ public abstract static class Result { abstract Schema getOutputSchema(); - static Result from( - JoinInformation joinInformation, - JoinArguments joinArgs, - Row key, - Schema outputSchema, - CoGbkResult coGbkResult, - DoFn.ProcessContext processContext) { - return from( - joinInformation, joinArgs, key, outputSchema, coGbkResult::getAll, processContext); - } - - static Result from( - JoinInformation joinInformation, - JoinArguments joinArgs, - Row key, - Schema outputSchema, - Row leftRow, - DoFn.ProcessContext processContext) { - return from( - joinInformation, - joinArgs, - key, - outputSchema, - t -> Lists.newArrayList(leftRow), - processContext); - } - - private static Result from( - JoinInformation joinInformation, - JoinArguments joinArgs, - Row key, - Schema outputSchema, - Function> leftSideSupplier, - DoFn.ProcessContext processContext) { - List> fields = - Lists.newArrayListWithCapacity(joinInformation.sortedTags.size()); - List tags = Lists.newArrayListWithCapacity(joinInformation.sortedTags.size()); - - for (int i = 0; i < joinInformation.sortedTags.size(); ++i) { - String tupleTag = joinInformation.tagToKeyedTag.get(i); - PCollectionView>> sideView = - joinInformation.sideInputs.get(tupleTag); - Iterable rows = - (sideView != null) - ? processContext.sideInput(sideView).get(key) - : leftSideSupplier.apply(tupleTag); - if (rows == null) { - rows = Collections::emptyIterator; - } - fields.add(rows); - tags.add(joinInformation.sortedTags.get(i)); - } - return new AutoValue_CoGroup_Result(key, fields, tags, joinArgs, outputSchema); - } - static Schema getUnexandedOutputSchema(String keyFieldName, JoinInformation joinInformation) { Schema.Builder schemaBuilder = Schema.builder().addRowField(keyFieldName, joinInformation.keySchema); @@ -541,13 +562,6 @@ static Schema getUnexandedOutputSchema(String keyFieldName, JoinInformation join return schemaBuilder.build(); } - void outputUnexpandedRow(Schema outputSchema, OutputReceiver o) { - List fields = Lists.newArrayListWithCapacity(getIterables().size() + 1); - fields.add(getKey()); - fields.addAll(getIterables()); - o.output(Row.withSchema(outputSchema).attachValues(fields)); - } - static void verifyExpandedArgs(JoinInformation joinInformation, JoinArguments joinArgs) { boolean hasSideInput = false; boolean allMainInputsOptional = true; @@ -579,120 +593,249 @@ static Schema getExpandedOutputSchema(JoinInformation joinInformation, JoinArgum } return joinedSchemaBuilder.build(); } + } - void outputExpandedRows(OutputReceiver o) { - List> allIterables = extractIterables(); - List accumulatedRows = Lists.newArrayListWithCapacity(getIterables().size()); - crossProduct(0, accumulatedRows, allIterables, o); - } - - private List> extractIterables() { - List> iterables = Lists.newArrayListWithCapacity(getIterables().size()); - for (int i = 0; i < getIterables().size(); ++i) { - Iterable items = getIterables().get(i); - String tag = getTags().get(i); - - if (!items.iterator().hasNext() && getJoinArguments().getOptionalParticipation(tag)) { - // If this tag has optional participation, then empty should participate as a - // single null. - items = () -> NULL_LIST.iterator(); - } - iterables.add(items); - } - return iterables; - } - - private void crossProduct( - int tagIndex, - List accumulatedRows, - List> iterables, - OutputReceiver o) { - if (tagIndex >= iterables.size()) { - return; - } - - for (Row row : iterables.get(tagIndex)) { - // For every item that joined for the current input, and recurse down to calculate the - // list of expanded records. - crossProductHelper(tagIndex, accumulatedRows, row, iterables, o); + private static void emitCrossProduct( + int index, + int fixedIndex, + @Nullable Object[] buffer, + Iterable[] iterables, + Schema outputSchema, + OutputReceiver o) { + boolean atBottom = index == iterables.length - 1; + if (index == fixedIndex) { + if (atBottom) { + o.output(Row.attachValues(outputSchema, buffer.clone())); + } else { + emitCrossProduct(index + 1, fixedIndex, buffer, iterables, outputSchema, o); } + return; } - - private void crossProductHelper( - int tagIndex, - List accumulatedRows, - Row newRow, - List> iterables, - OutputReceiver o) { - boolean atBottom = tagIndex == iterables.size() - 1; - accumulatedRows.add(newRow); + for (Row row : iterables[index]) { + buffer[index] = row; if (atBottom) { - // Bottom of recursive call, so output the row we've accumulated. - Row row = - Row.withSchema(getOutputSchema()).attachValues(Lists.newArrayList(accumulatedRows)); - o.output(row); + o.output(Row.attachValues(outputSchema, buffer.clone())); } else { - crossProduct(tagIndex + 1, accumulatedRows, iterables, o); + emitCrossProduct(index + 1, fixedIndex, buffer, iterables, outputSchema, o); } - accumulatedRows.remove(accumulatedRows.size() - 1); } } static class ConvertCoGbkResult extends DoFn, Row> { - private final JoinInformation joinInformation; - private final JoinArguments joinArgs; + private final int numInputs; + private final @Nullable TupleTag[] mainTags; + private final @Nullable PCollectionView>>[] sideViews; + private final boolean[] isOptional; private final Schema outputSchema; + private final boolean unexpanded; enum ConvertType { UNEXPANDED, EXPANDED - }; - - private ConvertType convertType; + } + @SuppressWarnings({"unchecked", "rawtypes"}) public ConvertCoGbkResult( JoinInformation joinInformation, JoinArguments joinArgs, ConvertType convertType, Schema outputSchema) { - this.joinInformation = joinInformation; - this.joinArgs = joinArgs; + this.numInputs = joinInformation.sortedTags.size(); + this.mainTags = new TupleTag[numInputs]; + this.sideViews = new PCollectionView[numInputs]; + this.isOptional = new boolean[numInputs]; + for (int i = 0; i < numInputs; i++) { + String tag = joinInformation.sortedTags.get(i); + String keyedTag = joinInformation.tagToKeyedTag.get(i); + PCollectionView>> sideView = + joinInformation.sideInputs.get(keyedTag); + if (sideView != null) { + this.sideViews[i] = sideView; + } else { + TupleTag existingTag = joinInformation.indexToTupleTag.get(i); + this.mainTags[i] = existingTag != null ? existingTag : new TupleTag<>(keyedTag); + } + this.isOptional[i] = joinArgs.getOptionalParticipation(tag); + } this.outputSchema = outputSchema; - this.convertType = convertType; + this.unexpanded = convertType == ConvertType.UNEXPANDED; } @ProcessElement + @SuppressWarnings({"unchecked", "rawtypes"}) public void process( @Element KV element, ProcessContext c, OutputReceiver o) { - Result result = - Result.from( - joinInformation, joinArgs, element.getKey(), outputSchema, element.getValue(), c); - if (convertType == ConvertType.UNEXPANDED) { - result.outputUnexpandedRow(outputSchema, o); - } else { - result.outputExpandedRows(o); + Row key = element.getKey(); + CoGbkResult coGbk = element.getValue(); + if (unexpanded) { + Object[] fields = new Object[numInputs + 1]; + fields[0] = key; + for (int i = 0; i < numInputs; i++) { + Iterable rows; + PCollectionView>> sideView = sideViews[i]; + if (sideView != null) { + rows = c.sideInput(sideView).get(key); + if (rows == null) { + rows = Collections.emptyList(); + } + } else { + rows = coGbk.getAll(mainTags[i]); + } + fields[i + 1] = rows; + } + o.output(Row.attachValues(outputSchema, fields)); + return; + } + + if (numInputs == 2) { + Iterable r0 = + sideViews[0] != null ? c.sideInput(sideViews[0]).get(key) : coGbk.getAll(mainTags[0]); + if (r0 == null || isEmpty(r0)) { + if (!isOptional[0]) { + return; + } + r0 = NULL_LIST; + } + Iterable r1 = + sideViews[1] != null ? c.sideInput(sideViews[1]).get(key) : coGbk.getAll(mainTags[1]); + if (r1 == null || isEmpty(r1)) { + if (!isOptional[1]) { + return; + } + r1 = NULL_LIST; + } + for (Row left : r0) { + for (Row right : r1) { + o.output(Row.attachValues(outputSchema, left, right)); + } + } + return; + } + + if (numInputs == 0) { + return; + } + Iterable[] iterables = new Iterable[numInputs]; + for (int i = 0; i < numInputs; i++) { + PCollectionView>> sideView = sideViews[i]; + Iterable rows = + sideView != null ? c.sideInput(sideView).get(key) : coGbk.getAll(mainTags[i]); + if (rows == null || isEmpty(rows)) { + if (!isOptional[i]) { + // Short-circuit: empty required side means the entire cross product is empty. + return; + } + rows = NULL_LIST; + } + iterables[i] = rows; } + @Nullable Object[] buffer = new Object[numInputs]; + emitCrossProduct(0, -1, buffer, iterables, outputSchema, o); } } - static class ExpandRowResult extends DoFn, Row> { - private final JoinInformation joinInformation; - private final JoinArguments joinArgs; + /** + * Fused single-main-input broadcast join {@link DoFn} that extracts the join key directly from + * each input element without an extra {@code extractKey} {@code ParDo} and {@code KV} allocation. + */ + static class FusedExpandBroadcastJoin extends DoFn { + private final int numInputs; + private final int mainIndex; + private final RowSelectorContainer keySelectorContainer; + private final @Nullable SerializableFunction toRowFunction; + private final @Nullable PCollectionView>>[] sideViews; + private final boolean[] isOptional; private final Schema outputSchema; + private transient @Nullable RowSelector keySelector; - public ExpandRowResult( - JoinInformation joinInformation, JoinArguments joinArgs, Schema outputSchema) { - this.joinInformation = joinInformation; - this.joinArgs = joinArgs; + @SuppressWarnings({"unchecked", "rawtypes"}) + FusedExpandBroadcastJoin( + JoinInformation joinInformation, + JoinArguments joinArgs, + Schema mainSchema, + FieldAccessDescriptor keyFields, + @Nullable SerializableFunction toRowFunction, + Schema outputSchema) { + this.numInputs = joinInformation.sortedTags.size(); + this.mainIndex = joinInformation.singleMainIndex; + this.keySelectorContainer = + new RowSelectorContainer(mainSchema, keyFields, joinInformation.keySchema, true); + this.toRowFunction = toRowFunction; + this.sideViews = new PCollectionView[numInputs]; + this.isOptional = new boolean[numInputs]; + for (int i = 0; i < numInputs; i++) { + String tag = joinInformation.sortedTags.get(i); + this.isOptional[i] = joinArgs.getOptionalParticipation(tag); + if (i != mainIndex) { + String keyedTag = joinInformation.tagToKeyedTag.get(i); + this.sideViews[i] = joinInformation.sideInputs.get(keyedTag); + } + } this.outputSchema = outputSchema; } + @Setup + public void setup() { + this.keySelector = keySelectorContainer.getOrCreateSelector(); + } + @ProcessElement - public void process(@Element KV element, ProcessContext c, OutputReceiver o) { - Result result = - Result.from( - joinInformation, joinArgs, element.getKey(), outputSchema, element.getValue(), c); - result.outputExpandedRows(o); + @SuppressWarnings({"unchecked", "rawtypes"}) + public void process(@Element T element, ProcessContext c, OutputReceiver o) { + Row mainRow = toRowFunction != null ? toRowFunction.apply(element) : (Row) element; + if (numInputs == 1) { + o.output(Row.attachValues(outputSchema, mainRow)); + return; + } + RowSelector selector = this.keySelector; + if (selector == null) { + selector = keySelectorContainer.getOrCreateSelector(); + this.keySelector = selector; + } + Row key = selector.select(mainRow); + + if (numInputs == 2) { + int sideIdx = 1 - mainIndex; + Iterable matches = c.sideInput(sideViews[sideIdx]).get(key); + if (matches == null || isEmpty(matches)) { + if (isOptional[sideIdx]) { + if (mainIndex == 0) { + o.output(Row.attachValues(outputSchema, mainRow, null)); + } else { + o.output(Row.attachValues(outputSchema, null, mainRow)); + } + } + return; + } + if (mainIndex == 0) { + for (Row sideRow : matches) { + o.output(Row.attachValues(outputSchema, mainRow, sideRow)); + } + } else { + for (Row sideRow : matches) { + o.output(Row.attachValues(outputSchema, sideRow, mainRow)); + } + } + return; + } + + Iterable[] iterables = new Iterable[numInputs]; + for (int i = 0; i < numInputs; i++) { + if (i == mainIndex) { + continue; + } + Iterable matches = c.sideInput(sideViews[i]).get(key); + if (matches == null || isEmpty(matches)) { + if (!isOptional[i]) { + return; + } + matches = NULL_LIST; + } + iterables[i] = matches; + } + @Nullable Object[] buffer = new Object[numInputs]; + buffer[mainIndex] = mainRow; + emitCrossProduct(0, mainIndex, buffer, iterables, outputSchema, o); } } @@ -741,7 +884,7 @@ public PCollection expand(PCollectionTuple input) { JoinInformation joinInformation = JoinInformation.from( - input, joinArgs::getFieldAccessDescriptor, joinArgs::getSideInputSource); + input, joinArgs::getFieldAccessDescriptor, joinArgs::getSideInputSource, false); Collection>>> views = joinInformation.sideInputs.values(); @@ -784,7 +927,7 @@ public PCollection expand(PCollectionTuple input) { JoinInformation joinInformation = JoinInformation.from( - input, joinArgs::getFieldAccessDescriptor, joinArgs::getSideInputSource); + input, joinArgs::getFieldAccessDescriptor, joinArgs::getSideInputSource, true); Result.verifyExpandedArgs(joinInformation, joinArgs); Schema outputSchema = Result.getExpandedOutputSchema(joinInformation, joinArgs); @@ -792,7 +935,9 @@ public PCollection expand(PCollectionTuple input) { joinInformation.sideInputs.values(); PCollection expanded; - if (joinInformation.keyedPCollectionTuple.getKeyedCollections().size() > 1) { + if (joinInformation.singleMainInput != null) { + expanded = applyFusedBroadcastJoin(joinInformation, joinArgs, outputSchema, views); + } else { expanded = joinInformation .keyedPCollectionTuple @@ -802,18 +947,32 @@ public PCollection expand(PCollectionTuple input) { new ConvertCoGbkResult( joinInformation, joinArgs, ConvertType.EXPANDED, outputSchema)) .withSideInputs(views)); - } else { - TaggedKeyedPCollection tpc = - (TaggedKeyedPCollection) - Iterables.getOnlyElement( - joinInformation.keyedPCollectionTuple.getKeyedCollections()); - expanded = - tpc.getCollection() - .apply( - ParDo.of(new ExpandRowResult(joinInformation, joinArgs, outputSchema)) - .withSideInputs(views)); } return expanded.setRowSchema(outputSchema); } + + @SuppressWarnings("unchecked") + private static PCollection applyFusedBroadcastJoin( + JoinInformation joinInformation, + JoinArguments joinArgs, + Schema outputSchema, + Collection>>> views) { + PCollection mainPc = (PCollection) joinInformation.singleMainInput; + Schema mainSchema = mainPc.getSchema(); + @Nullable SerializableFunction toRowFn = + SchemaUtils.isIdentityFunction(mainPc.getToRowFunction()) + ? null + : mainPc.getToRowFunction(); + return mainPc.apply( + ParDo.of( + new FusedExpandBroadcastJoin<>( + joinInformation, + joinArgs, + mainSchema, + joinInformation.singleMainKeyDescriptor, + toRowFn, + outputSchema)) + .withSideInputs(views)); + } } } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/CoGroupTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/CoGroupTest.java index 7788b37ad8f8..82429208b936 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/CoGroupTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/CoGroupTest.java @@ -867,6 +867,46 @@ public void testPojo() { pipeline.run(); } + @Test + @Category(NeedsRunner.class) + public void testBroadcastJoinWithNestedWidenedKeySchema() { + Schema mainKeySchema = Schema.builder().addStringField("id").build(); + Schema sideKeySchema = Schema.builder().addNullableStringField("id").build(); + Schema mainSchema = + Schema.builder().addRowField("k", mainKeySchema).addInt32Field("v1").build(); + Schema sideSchema = + Schema.builder().addRowField("k", sideKeySchema).addStringField("v2").build(); + + Row mainRow = + Row.withSchema(mainSchema) + .addValues(Row.withSchema(mainKeySchema).addValues("a").build(), 10) + .build(); + Row sideRow = + Row.withSchema(sideSchema) + .addValues(Row.withSchema(sideKeySchema).addValues("a").build(), "matched") + .build(); + + PCollection mainPc = + pipeline.apply("CreateMain", Create.of(mainRow)).setRowSchema(mainSchema); + PCollection sidePc = + pipeline.apply("CreateSide", Create.of(sideRow)).setRowSchema(sideSchema); + + PCollection joined = + PCollectionTuple.of("main", mainPc) + .and("side", sidePc) + .apply( + CoGroup.join("main", By.fieldNames("k")) + .join("side", By.fieldNames("k").withSideInput()) + .crossProductJoin()); + + Schema expectedSchema = + Schema.builder().addRowField("main", mainSchema).addRowField("side", sideSchema).build(); + PAssert.that(joined) + .containsInAnyOrder(Row.withSchema(expectedSchema).addValues(mainRow, sideRow).build()); + + pipeline.run(); + } + private static Void containsJoinedFields(List expected, Iterable actual) { List> matchers = Lists.newArrayList(); for (Row row : expected) { From 079d2d9f8d325d5a08f6cf7290571fb373bd1a81 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:57:16 -0800 Subject: [PATCH 10/15] Optimize DoFnSchemaInformation field binding and lazy DoFnInvokerBase timer maps Shares Row conversion across multi-parameter @FieldAccess DoFn invocations, reads single-field paths directly via SchemaUtils.readFieldPath, and initializes DoFnInvokerBase timer maps lazily. --- .../sdk/transforms/DoFnSchemaInformation.java | 77 ++++++++++++++----- .../reflect/ByteBuddyDoFnInvokerFactory.java | 14 +++- 2 files changed, 69 insertions(+), 22 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnSchemaInformation.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnSchemaInformation.java index cbb9e87f2afa..0604f069b166 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnSchemaInformation.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnSchemaInformation.java @@ -26,6 +26,7 @@ import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.schemas.SchemaCoder; +import org.apache.beam.sdk.schemas.SchemaUtils; import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.DefaultTypeConversionsFactory; import org.apache.beam.sdk.schemas.utils.ConvertHelpers; import org.apache.beam.sdk.schemas.utils.RowSelector; @@ -33,6 +34,7 @@ import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptor; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; +import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.qual.Pure; /** Represents information about how a DoFn extracts schemas. */ @@ -171,7 +173,9 @@ private static class ConversionFunction private final SerializableFunction toRowFunction; private final SerializableFunction fromRowFunction; private final boolean unbox; - private final RowSelector rowSelector; + private final boolean selectAll; + private final int @Nullable [] directUnboxPath; + private final @Nullable RowSelector rowSelector; private ConversionFunction( Schema inputSchema, @@ -182,7 +186,21 @@ private ConversionFunction( this.toRowFunction = toRowFunction; this.fromRowFunction = fromRowFunction; this.unbox = unbox; - this.rowSelector = new RowSelectorContainer(inputSchema, selectDescriptor, true); + if (selectDescriptor.getAllFields()) { + this.selectAll = true; + this.directUnboxPath = null; + this.rowSelector = null; + } else if (unbox) { + int[] path = SchemaUtils.tryResolveSingleFieldPath(inputSchema, selectDescriptor); + this.selectAll = false; + this.directUnboxPath = path; + this.rowSelector = + path == null ? new RowSelectorContainer(inputSchema, selectDescriptor, true) : null; + } else { + this.selectAll = false; + this.directUnboxPath = null; + this.rowSelector = new RowSelectorContainer(inputSchema, selectDescriptor, true); + } } public static ConversionFunction of( @@ -198,9 +216,16 @@ public static ConversionFunction of( @Override public OutputT apply(InputT input) { Row row = toRowFunction.apply(input); - Row selected = rowSelector.select(row); - if (unbox) { - selected = selected.getRow(0); + Row selected; + if (selectAll) { + selected = (unbox && row != null) ? row.getRow(0) : row; + } else if (directUnboxPath != null) { + selected = (Row) SchemaUtils.readFieldPath(row, directUnboxPath); + } else { + selected = rowSelector.select(row); + if (unbox && selected != null) { + selected = selected.getRow(0); + } } return fromRowFunction.apply(selected); } @@ -215,8 +240,10 @@ private static class UnboxingConversionFunction private final SerializableFunction toRowFunction; private final FieldType primitiveType; private final TypeDescriptor primitiveOutputType; - private transient SerializableFunction conversionFunction; - private final RowSelector rowSelector; + private final int @Nullable [] directPath; + private final @Nullable RowSelector rowSelector; + private transient volatile @Nullable SerializableFunction conversionFunction; + private transient volatile boolean isIdentityConversion; private UnboxingConversionFunction( Schema inputSchema, @@ -227,7 +254,10 @@ private UnboxingConversionFunction( this.toRowFunction = toRowFunction; this.primitiveType = selectOutputSchema.getField(0).getType(); this.primitiveOutputType = primitiveOutputType; - this.rowSelector = new RowSelectorContainer(inputSchema, selectDescriptor, true); + int[] path = SchemaUtils.tryResolveSingleFieldPath(inputSchema, selectDescriptor); + this.directPath = path; + this.rowSelector = + path == null ? new RowSelectorContainer(inputSchema, selectDescriptor, true) : null; } public static UnboxingConversionFunction of( @@ -241,20 +271,31 @@ public static UnboxingConversionFunction of( } @Override + @SuppressWarnings("unchecked") public OutputT apply(InputT input) { Row row = toRowFunction.apply(input); - Row selected = rowSelector.select(row); - return getConversionFunction().apply(selected.getValue(0)); + Object value; + if (directPath != null) { + value = SchemaUtils.readFieldPath(row, directPath); + } else { + value = rowSelector.select(row).getValue(0); + } + SerializableFunction conv = this.conversionFunction; + if (conv == null) { + conv = initConversionFunction(); + } + return isIdentityConversion ? (OutputT) value : conv.apply(value); } - private SerializableFunction getConversionFunction() { - if (conversionFunction == null) { - conversionFunction = - (SerializableFunction) - ConvertHelpers.getConvertPrimitive( - primitiveType, primitiveOutputType, new DefaultTypeConversionsFactory()); - } - return conversionFunction; + @SuppressWarnings("unchecked") + private SerializableFunction initConversionFunction() { + SerializableFunction fn = + ConvertHelpers.getConvertPrimitive( + primitiveType, primitiveOutputType, DefaultTypeConversionsFactory.INSTANCE); + isIdentityConversion = SchemaUtils.isIdentityFunction(fn); + SerializableFunction typed = (SerializableFunction) fn; + this.conversionFunction = typed; + return typed; } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/reflect/ByteBuddyDoFnInvokerFactory.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/reflect/ByteBuddyDoFnInvokerFactory.java index 9d307a4e0a98..79dfd18b7cd9 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/reflect/ByteBuddyDoFnInvokerFactory.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/reflect/ByteBuddyDoFnInvokerFactory.java @@ -280,8 +280,8 @@ public abstract static class DoFnInvokerBase { protected DoFnT delegate; - private Map onTimerInvokers = Maps.newHashMap(); - private Map onTimerFamilyInvokers = Maps.newHashMap(); + private @Nullable Map onTimerInvokers; + private @Nullable Map onTimerFamilyInvokers; public DoFnInvokerBase(DoFnT delegate) { this.delegate = delegate; @@ -297,6 +297,9 @@ public DoFnInvokerBase(DoFnT delegate) { * DoFnInvokerBase} not by any subclass. */ void addOnTimerInvoker(String timerId, OnTimerInvoker onTimerInvoker) { + if (this.onTimerInvokers == null) { + this.onTimerInvokers = Maps.newHashMap(); + } this.onTimerInvokers.put(timerId, onTimerInvoker); } @@ -307,6 +310,9 @@ void addOnTimerInvoker(String timerId, OnTimerInvoker onTimerInvoker) { * timer ID rather than a generated conditional branch to choose which OnTimerInvoker to invoke. */ void addOnTimerFamilyInvoker(String timerFamilyId, OnTimerInvoker onTimerInvoker) { + if (this.onTimerFamilyInvokers == null) { + this.onTimerFamilyInvokers = Maps.newHashMap(); + } this.onTimerFamilyInvokers.put(timerFamilyId, onTimerInvoker); } @@ -317,8 +323,8 @@ public void invokeOnTimer( DoFnInvoker.ArgumentProvider arguments) { @Nullable OnTimerInvoker onTimerInvoker = timerFamilyId.isEmpty() - ? onTimerInvokers.get(timerId) - : onTimerFamilyInvokers.get(timerFamilyId); + ? (onTimerInvokers != null ? onTimerInvokers.get(timerId) : null) + : (onTimerFamilyInvokers != null ? onTimerFamilyInvokers.get(timerFamilyId) : null); if (onTimerInvoker != null) { onTimerInvoker.invokeOnTimer(arguments); From b525c21d236374cca1c13d8bb2a8d51f4c6c80ff Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:58:06 -0800 Subject: [PATCH 11/15] Optimize JsonUtils, RowJsonUtils, and Java schema transform providers Reduces per-record JSON and YAML Java provider allocations and recompilation overhead: - JsonUtils / RowJsonUtils: reuses ObjectReader/ObjectWriter and adds direct UTF-8 byte[] serialization/deserialization without intermediate Strings. - JavaExplode / JavaFilter / JavaMapToFields / JavaRowUdf / StringCompiler / LoggingTransformProvider: caches compiled UDF classes, skips guessExpressionType on reload, uses indexed array/Row.attachValues access, and adds SLF4J level guards. --- .../JavaExplodeTransformProvider.java | 173 +++++++++++---- .../JavaFilterTransformProvider.java | 76 +++++-- .../JavaMapToFieldsTransformProvider.java | 203 ++++++++++++++---- .../transforms/providers/JavaRowUdf.java | 199 ++++++++++++----- .../providers/LoggingTransformProvider.java | 18 +- .../transforms/providers/StringCompiler.java | 86 +++++--- .../beam/sdk/schemas/utils/JsonUtils.java | 57 +++-- .../apache/beam/sdk/util/RowJsonUtils.java | 44 ++++ .../JavaMapToFieldsTransformProviderTest.java | 67 ++++++ 9 files changed, 727 insertions(+), 196 deletions(-) diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaExplodeTransformProvider.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaExplodeTransformProvider.java index 48ce5e33d9fa..fd46099d75cc 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaExplodeTransformProvider.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaExplodeTransformProvider.java @@ -19,11 +19,11 @@ import com.google.auto.service.AutoService; import com.google.auto.value.AutoValue; +import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; import javax.annotation.Nullable; import org.apache.beam.sdk.schemas.AutoValueSchema; import org.apache.beam.sdk.schemas.Schema; @@ -36,8 +36,7 @@ import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionRowTuple; import org.apache.beam.sdk.values.Row; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.primitives.Booleans; +import org.apache.beam.sdk.values.RowWithStorage; /** * An implementation of {@link TypedSchemaTransformProvider} for Explode. @@ -162,60 +161,160 @@ private static DoFn createDoFn( } else { crossProduct = crossProductObj; } - int numFields = outputSchema.getFields().size(); - boolean[] toExplode = - Booleans.toArray( - IntStream.range(0, numFields) - .mapToObj(index -> fields.contains(outputSchema.getField(index).getName())) - .collect(Collectors.toList())); + int numFields = outputSchema.getFieldCount(); + List explodeList = new ArrayList<>(fields.size()); + List copyList = new ArrayList<>(numFields); + for (int i = 0; i < numFields; i++) { + if (fields.contains(outputSchema.getField(i).getName())) { + explodeList.add(i); + } else { + copyList.add(i); + } + } + int[] explodeIndices = new int[explodeList.size()]; + for (int i = 0; i < explodeList.size(); i++) { + explodeIndices[i] = explodeList.get(i); + } + int[] copyIndices = new int[copyList.size()]; + for (int i = 0; i < copyList.size(); i++) { + copyIndices[i] = copyList.get(i); + } + + if (explodeIndices.length == 1) { + final int explodeIdx = explodeIndices[0]; + return new DoFn() { + @ProcessElement + public void processElement(@Element Row inputRow, OutputReceiver out) { + Iterable iterable = inputRow.getIterable(explodeIdx); + if (iterable == null) { + return; + } + if (iterable instanceof Collection && ((Collection) iterable).isEmpty()) { + return; + } + Iterator iter = iterable.iterator(); + if (!iter.hasNext()) { + return; + } + Object[] template = new Object[numFields]; + Object[] raw = + inputRow instanceof RowWithStorage + ? ((RowWithStorage) inputRow).getRawArray() + : null; + for (int c : copyIndices) { + template[c] = raw != null ? raw[c] : inputRow.getValue(c); + } + while (iter.hasNext()) { + Object[] rowValues = template.clone(); + rowValues[explodeIdx] = iter.next(); + out.output(Row.attachValues(outputSchema, rowValues)); + } + } + }; + } + if (crossProduct) { return new DoFn() { @ProcessElement + @SuppressWarnings("rawtypes") public void processElement(@Element Row inputRow, OutputReceiver out) { - emitCrossProduct(inputRow, 0, new Object[numFields], out); + int k = explodeIndices.length; + if (k == 0) { + out.output(inputRow); + return; + } + Iterable[] iterables = new Iterable[k]; + for (int i = 0; i < k; i++) { + Iterable it = inputRow.getIterable(explodeIndices[i]); + if (it == null) { + return; + } + if (it instanceof Collection) { + if (((Collection) it).isEmpty()) { + return; + } + } else if (i > 0 && !it.iterator().hasNext()) { + return; + } + iterables[i] = it; + } + Object[] current = new Object[numFields]; + Object[] raw = + inputRow instanceof RowWithStorage + ? ((RowWithStorage) inputRow).getRawArray() + : null; + for (int c : copyIndices) { + current[c] = raw != null ? raw[c] : inputRow.getValue(c); + } + emitCrossProduct(iterables, 0, current, out); } + @SuppressWarnings("rawtypes") private void emitCrossProduct( - Row inputRow, int index, Object[] current, OutputReceiver out) { - if (index == numFields) { - out.output(Row.withSchema(outputSchema).attachValues(ImmutableList.copyOf(current))); - } else if (toExplode[index]) { - for (Object value : inputRow.getIterable(index)) { - current[index] = value; - emitCrossProduct(inputRow, index + 1, current, out); + Iterable[] iterables, int pos, Object[] current, OutputReceiver out) { + int fieldIdx = explodeIndices[pos]; + boolean atBottom = pos == explodeIndices.length - 1; + for (Object value : iterables[pos]) { + current[fieldIdx] = value; + if (atBottom) { + out.output(Row.attachValues(outputSchema, current.clone())); + } else { + emitCrossProduct(iterables, pos + 1, current, out); } - } else { - current[index] = inputRow.getValue(index); - emitCrossProduct(inputRow, index + 1, current, out); } } }; } else { return new DoFn() { @ProcessElement + @SuppressWarnings("rawtypes") public void processElement(@Element Row inputRow, OutputReceiver out) { - @SuppressWarnings("rawtypes") - Iterator[] iterators = new Iterator[numFields]; - for (int i = 0; i < numFields; i++) { - if (toExplode[i]) { - iterators[i] = inputRow.getIterable(i).iterator(); + int k = explodeIndices.length; + if (k == 0) { + return; + } + Iterator[] iterators = new Iterator[k]; + boolean anyNext = false; + for (int i = 0; i < k; i++) { + Iterable it = inputRow.getIterable(explodeIndices[i]); + Iterator iter = it == null ? Collections.emptyIterator() : it.iterator(); + iterators[i] = iter; + if (iter.hasNext()) { + anyNext = true; } } - while (IntStream.range(0, numFields) - .anyMatch(index -> toExplode[index] && iterators[index].hasNext())) { - Row.Builder builder = Row.withSchema(outputSchema); - for (int i = 0; i < numFields; i++) { - if (toExplode[i]) { - if (iterators[i].hasNext()) { - builder.addValue(iterators[i].next()); - } else { - builder.addValue(null); + if (!anyNext) { + return; + } + Object[] template = new Object[numFields]; + Object[] raw = + inputRow instanceof RowWithStorage + ? ((RowWithStorage) inputRow).getRawArray() + : null; + for (int c : copyIndices) { + template[c] = raw != null ? raw[c] : inputRow.getValue(c); + } + while (anyNext) { + Object[] rowValues = template.clone(); + anyNext = false; + for (int i = 0; i < k; i++) { + Iterator iter = iterators[i]; + if (iter.hasNext()) { + rowValues[explodeIndices[i]] = iter.next(); + if (iter.hasNext()) { + anyNext = true; } } else { - builder.addValue(inputRow.getValue(i)); + int fieldIdx = explodeIndices[i]; + if (!outputSchema.isFieldNullable(fieldIdx)) { + throw new IllegalArgumentException( + "Cannot set null on non-nullable field " + + outputSchema.getField(fieldIdx).getName()); + } + rowValues[fieldIdx] = null; } } - out.output(builder.build()); + out.output(Row.attachValues(outputSchema, rowValues)); } } }; diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaFilterTransformProvider.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaFilterTransformProvider.java index 4ae8d2e41b30..38f865689516 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaFilterTransformProvider.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaFilterTransformProvider.java @@ -22,6 +22,7 @@ import java.net.MalformedURLException; import java.util.Collections; import java.util.List; +import java.util.function.Function; import javax.annotation.Nullable; import org.apache.beam.sdk.schemas.AutoValueSchema; import org.apache.beam.sdk.schemas.Schema; @@ -31,6 +32,7 @@ import org.apache.beam.sdk.schemas.transforms.TypedSchemaTransformProvider; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionRowTuple; import org.apache.beam.sdk.values.PCollectionTuple; import org.apache.beam.sdk.values.Row; @@ -133,43 +135,85 @@ public PCollectionRowTuple expand(PCollectionRowTuple input) { this.configuration.getKeep(), keepFn.getOutputType())); } boolean handleErrors = ErrorHandling.hasOutput(configuration.getErrorHandling()); + if (!handleErrors) { + PCollection filtered = + input + .get(INPUT_ROWS_TAG) + .apply("Filter", ParDo.of(createSimpleDoFn(keepFn))) + .setRowSchema(inputSchema); + return PCollectionRowTuple.of(OUTPUT_ROWS_TAG, filtered); + } Schema errorSchema = ErrorHandling.errorSchema(inputSchema); - PCollectionTuple pcolls = input .get(INPUT_ROWS_TAG) .apply( "Filter", - ParDo.of(createDoFn(keepFn, errorSchema, handleErrors)) + ParDo.of(createErrorHandlingDoFn(keepFn, errorSchema)) .withOutputTags(filteredValues, TupleTagList.of(errorValues))); pcolls.get(filteredValues).setRowSchema(inputSchema); pcolls.get(errorValues).setRowSchema(errorSchema); - PCollectionRowTuple result = - PCollectionRowTuple.of(OUTPUT_ROWS_TAG, pcolls.get(filteredValues)); - if (handleErrors) { - result = result.and(configuration.getErrorHandling().getOutput(), pcolls.get(errorValues)); - } - return result; + return PCollectionRowTuple.of(OUTPUT_ROWS_TAG, pcolls.get(filteredValues)) + .and(configuration.getErrorHandling().getOutput(), pcolls.get(errorValues)); } private static final TupleTag filteredValues = new TupleTag() {}; private static final TupleTag errorValues = new TupleTag() {}; - private static DoFn createDoFn( - JavaRowUdf keepFn, Schema errorSchema, boolean handleErrors) { + private static Function resolveKeepFn(JavaRowUdf keepFn) { + try { + return keepFn.getFunction(); + } catch (Exception exn) { + throw new RuntimeException(exn); + } + } + + private static DoFn createSimpleDoFn(JavaRowUdf keepFn) { + return new DoFn() { + private transient Function fn; + + @Setup + public void setup() { + this.fn = resolveKeepFn(keepFn); + } + + @ProcessElement + public void processElement(@Element Row inputRow, OutputReceiver out) { + Function localFn = this.fn; + if (localFn == null) { + localFn = resolveKeepFn(keepFn); + this.fn = localFn; + } + if ((boolean) localFn.apply(inputRow)) { + out.output(inputRow); + } + } + }; + } + + private static DoFn createErrorHandlingDoFn(JavaRowUdf keepFn, Schema errorSchema) { return new DoFn() { + private transient Function fn; + + @Setup + public void setup() { + this.fn = resolveKeepFn(keepFn); + } + @ProcessElement public void processElement(@Element Row inputRow, MultiOutputReceiver out) { boolean keep = false; try { - keep = (boolean) keepFn.getFunction().apply(inputRow); - } catch (Exception exn) { - if (handleErrors) { - out.get(errorValues).output(ErrorHandling.errorRecord(errorSchema, inputRow, exn)); - } else { - throw new RuntimeException(exn); + Function localFn = this.fn; + if (localFn == null) { + localFn = resolveKeepFn(keepFn); + this.fn = localFn; } + keep = (boolean) localFn.apply(inputRow); + } catch (Exception exn) { + out.get(errorValues).output(ErrorHandling.errorRecord(errorSchema, inputRow, exn)); + return; } if (keep) { out.get(filteredValues).output(inputRow); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProvider.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProvider.java index 4a75c73c46f5..6aa23b0b4946 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProvider.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProvider.java @@ -22,8 +22,11 @@ import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.function.Function; import javax.annotation.Nullable; import org.apache.beam.sdk.schemas.AutoValueSchema; import org.apache.beam.sdk.schemas.Schema; @@ -33,9 +36,11 @@ import org.apache.beam.sdk.schemas.transforms.TypedSchemaTransformProvider; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionRowTuple; import org.apache.beam.sdk.values.PCollectionTuple; import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.RowWithStorage; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.TupleTagList; @@ -134,26 +139,26 @@ public PCollectionRowTuple expand(PCollectionRowTuple input) { // TODO(yaml): Consider allowing the full java schema naming syntax // (perhaps as a different dialect/language). boolean append = configuration.getAppend() != null && configuration.getAppend(); - List toDrop = - configuration.getDrop() == null ? Collections.emptyList() : configuration.getDrop(); - List udfs = new ArrayList<>(); + Set toDrop = + configuration.getDrop() == null + ? Collections.emptySet() + : new HashSet<>(configuration.getDrop()); + List passThroughList = new ArrayList<>(); if (append) { - for (Schema.Field field : inputSchema.getFields()) { + for (int i = 0; i < inputSchema.getFieldCount(); i++) { + Schema.Field field = inputSchema.getField(i); if (!toDrop.contains(field.getName())) { - try { - udfs.add( - new JavaRowUdf( - JavaRowUdf.Configuration.builder().setExpression(field.getName()).build(), - inputSchema)); - } catch (MalformedURLException - | ReflectiveOperationException - | StringCompiler.CompileException exn) { - throw new RuntimeException(exn); - } + passThroughList.add(i); outputSchemaBuilder = outputSchemaBuilder.addField(field); } } } + int[] passThroughIndices = new int[passThroughList.size()]; + for (int i = 0; i < passThroughIndices.length; i++) { + passThroughIndices[i] = passThroughList.get(i); + } + + List udfs = new ArrayList<>(configuration.getFields().size()); for (Map.Entry entry : configuration.getFields().entrySet()) { try { @@ -168,52 +173,176 @@ public PCollectionRowTuple expand(PCollectionRowTuple input) { } Schema outputSchema = outputSchemaBuilder.build(); boolean handleErrors = ErrorHandling.hasOutput(configuration.getErrorHandling()); - Schema errorSchema = ErrorHandling.errorSchema(inputSchema); + if (!handleErrors) { + PCollection mapped = + input + .get(INPUT_ROWS_TAG) + .apply( + "MapToFields", + ParDo.of(createSimpleDoFn(passThroughIndices, udfs, outputSchema))) + .setRowSchema(outputSchema); + return PCollectionRowTuple.of(OUTPUT_ROWS_TAG, mapped); + } + Schema errorSchema = ErrorHandling.errorSchema(inputSchema); PCollectionTuple pcolls = input .get(INPUT_ROWS_TAG) .apply( "MapToFields", - ParDo.of(createDoFn(udfs, outputSchema, errorSchema, handleErrors)) + ParDo.of( + createErrorHandlingDoFn( + passThroughIndices, udfs, outputSchema, errorSchema)) .withOutputTags(mappedValues, TupleTagList.of(errorValues))); pcolls.get(mappedValues).setRowSchema(outputSchema); pcolls.get(errorValues).setRowSchema(errorSchema); - PCollectionRowTuple result = - PCollectionRowTuple.of(OUTPUT_ROWS_TAG, pcolls.get(mappedValues)); - if (handleErrors) { - result = result.and(configuration.getErrorHandling().getOutput(), pcolls.get(errorValues)); - } - return result; + return PCollectionRowTuple.of(OUTPUT_ROWS_TAG, pcolls.get(mappedValues)) + .and(configuration.getErrorHandling().getOutput(), pcolls.get(errorValues)); } private static final TupleTag mappedValues = new TupleTag() {}; private static final TupleTag errorValues = new TupleTag() {}; - private static DoFn createDoFn( - List udfs, Schema outputSchema, Schema errorSchema, boolean handleErrors) { + @SuppressWarnings({"unchecked", "rawtypes"}) + private static Function[] resolveFunctions(List udfs) { + Function[] fns = new Function[udfs.size()]; + for (int i = 0; i < udfs.size(); i++) { + try { + fns[i] = udfs.get(i).getFunction(); + } catch (Exception exn) { + throw new RuntimeException(exn); + } + } + return fns; + } + + private static boolean matchesExactScalarType(Schema.FieldType fieldType, Object val) { + switch (fieldType.getTypeName()) { + case STRING: + return val instanceof String; + case INT64: + return val instanceof Long; + case INT32: + return val instanceof Integer; + case DOUBLE: + return val instanceof Double; + case FLOAT: + return val instanceof Float; + case BOOLEAN: + return val instanceof Boolean; + case INT16: + return val instanceof Short; + case BYTE: + return val instanceof Byte; + case BYTES: + return val instanceof byte[]; + case DECIMAL: + return val instanceof java.math.BigDecimal; + case DATETIME: + return val instanceof org.joda.time.Instant; + default: + return false; + } + } + + private static Row mapRow( + Row inputRow, + int[] passThroughIndices, + Function[] fns, + Schema.FieldType[] udfFieldTypes, + Schema outputSchema) { + int passLen = passThroughIndices.length; + int fnLen = fns.length; + Object[] values = new Object[passLen + fnLen]; + if (passLen > 0) { + Object[] raw = + inputRow instanceof RowWithStorage ? ((RowWithStorage) inputRow).getRawArray() : null; + for (int i = 0; i < passLen; i++) { + int idx = passThroughIndices[i]; + values[i] = raw != null ? raw[idx] : inputRow.getValue(idx); + } + } + boolean needsValidation = false; + for (int i = 0; i < fnLen; i++) { + Object val = fns[i].apply(inputRow); + Schema.FieldType ft = udfFieldTypes[i]; + if (val == null) { + if (!ft.getNullable()) { + throw new IllegalArgumentException( + "Field " + outputSchema.getField(passLen + i).getName() + " is not nullable."); + } + } else if (!matchesExactScalarType(ft, val)) { + needsValidation = true; + } + values[passLen + i] = val; + } + if (needsValidation) { + return Row.withSchema(outputSchema).addValues(values).build(); + } + return Row.attachValues(outputSchema, values); + } + + private static Schema.FieldType[] extractUdfFieldTypes(int passLen, Schema outputSchema) { + int fnLen = outputSchema.getFieldCount() - passLen; + Schema.FieldType[] types = new Schema.FieldType[fnLen]; + for (int i = 0; i < fnLen; i++) { + types[i] = outputSchema.getField(passLen + i).getType(); + } + return types; + } + + private static DoFn createSimpleDoFn( + int[] passThroughIndices, List udfs, Schema outputSchema) { + Schema.FieldType[] udfFieldTypes = + extractUdfFieldTypes(passThroughIndices.length, outputSchema); return new DoFn() { + private transient Function[] fns; + + @Setup + public void setup() { + this.fns = resolveFunctions(udfs); + } + + @ProcessElement + public void processElement(@Element Row inputRow, OutputReceiver out) { + Function[] localFns = this.fns; + if (localFns == null) { + localFns = resolveFunctions(udfs); + this.fns = localFns; + } + out.output(mapRow(inputRow, passThroughIndices, localFns, udfFieldTypes, outputSchema)); + } + }; + } + + private static DoFn createErrorHandlingDoFn( + int[] passThroughIndices, List udfs, Schema outputSchema, Schema errorSchema) { + Schema.FieldType[] udfFieldTypes = + extractUdfFieldTypes(passThroughIndices.length, outputSchema); + return new DoFn() { + private transient Function[] fns; + + @Setup + public void setup() { + this.fns = resolveFunctions(udfs); + } + @ProcessElement public void processElement(@Element Row inputRow, MultiOutputReceiver out) { Row outputRow; try { - Row.Builder builder = Row.withSchema(outputSchema); - for (JavaRowUdf udf : udfs) { - builder.addValue(udf.getFunction().apply(inputRow)); + Function[] localFns = this.fns; + if (localFns == null) { + localFns = resolveFunctions(udfs); + this.fns = localFns; } - outputRow = builder.build(); + outputRow = mapRow(inputRow, passThroughIndices, localFns, udfFieldTypes, outputSchema); } catch (Exception exn) { - if (handleErrors) { - out.get(errorValues).output(ErrorHandling.errorRecord(errorSchema, inputRow, exn)); - outputRow = null; - } else { - throw new RuntimeException(exn); - } - } - if (outputRow != null) { - out.get(mappedValues).output(outputRow); + out.get(errorValues).output(ErrorHandling.errorRecord(errorSchema, inputRow, exn)); + return; } + out.get(mappedValues).output(outputRow); } }; } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaRowUdf.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaRowUdf.java index 2f0af657c03c..9d950b76bbf9 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaRowUdf.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaRowUdf.java @@ -24,7 +24,8 @@ import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; @@ -36,9 +37,10 @@ import java.nio.channels.ReadableByteChannel; import java.nio.file.StandardOpenOption; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -72,8 +74,11 @@ public class JavaRowUdf implements Serializable { // Transient so we don't have to worry about issues serializing these dynamically created classes. // While this is lazily computed, it is always computed on class construction, so any errors // should still be caught at construction time, and lazily re-computed before any use. + private static final ConcurrentHashMap DOWNLOADED_JARS = + new ConcurrentHashMap<>(); + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") - private transient Function function; + private transient volatile Function function; // Find or implement the inverse of StaticSchemaInference.fieldFromType @DefaultSchema(AutoValueSchema.class) @@ -144,12 +149,23 @@ public Schema.FieldType getOutputType() { public Function getFunction() throws MalformedURLException, ReflectiveOperationException, StringCompiler.CompileException { - if (function == null) { - FunctionAndType functionAndType = createFunction(config, inputSchema); - assert functionAndType.outputType.equals(outputType); - function = functionAndType.function; + Function fn = function; + if (fn == null) { + fn = createFunctionOnly(config, inputSchema); + function = fn; + } + return fn; + } + + @SuppressWarnings({ + "nullness" // TODO(https://github.com/apache/beam/issues/20497) + }) + private static Function createFunctionOnly(Configuration config, Schema inputSchema) + throws ReflectiveOperationException, StringCompiler.CompileException, MalformedURLException { + if (!Strings.isNullOrEmpty(config.getExpression())) { + return createExpressionFunctionOnly(config.getExpression(), inputSchema); } - return function; + return createFunction(config, inputSchema).function; } private static class FunctionAndType { @@ -200,6 +216,76 @@ private static FunctionAndType createFunction(Configuration config, Schema input } } + private static boolean containsIdentifier(String expression, String name) { + int nameLen = name.length(); + if (nameLen == 0) { + return false; + } + int from = 0; + int exprLen = expression.length(); + while (true) { + int idx = expression.indexOf(name, from); + if (idx == -1) { + return false; + } + boolean leftBoundary = + idx == 0 || !Character.isJavaIdentifierPart(expression.charAt(idx - 1)); + int end = idx + nameLen; + boolean rightBoundary = + end == exprLen || !Character.isJavaIdentifierPart(expression.charAt(end)); + if (leftBoundary && rightBoundary) { + return true; + } + from = idx + 1; + } + } + + private static Map referencedFieldTypes(String expression, Schema inputSchema) { + Map fieldTypes = new LinkedHashMap<>(); + for (Schema.Field field : inputSchema.getFields()) { + String name = field.getName(); + if (containsIdentifier(expression, name)) { + fieldTypes.put(name, typeFromFieldType(field.getType())); + } + } + return fieldTypes; + } + + @SuppressWarnings("unchecked") + private static Function compileExpressionFunction( + String expression, Schema inputSchema, Map fieldTypes) + throws StringCompiler.CompileException, ReflectiveOperationException { + StringBuilder source = new StringBuilder(); + source.append("import java.util.function.Function;\n"); + source.append("import " + Row.class.getTypeName() + ";\n"); + source.append("public class Eval implements Function {\n"); + source.append(" public Object apply(Row __row__) {\n"); + for (Map.Entry fieldEntry : fieldTypes.entrySet()) { + source.append( + String.format( + " %s %s = (%s) __row__.getValue(%s);%n", + fieldEntry.getValue().getTypeName(), + fieldEntry.getKey(), + fieldEntry.getValue().getTypeName(), + inputSchema.indexOf(fieldEntry.getKey()))); + } + source.append(" return " + expression + ";\n"); + source.append(" }\n"); + source.append("}\n"); + return (Function) StringCompiler.getInstance("Eval", source.toString()); + } + + private static Function createExpressionFunctionOnly( + String expression, Schema inputSchema) + throws StringCompiler.CompileException, ReflectiveOperationException { + if (inputSchema.hasField(expression)) { + final int ix = inputSchema.indexOf(expression); + return (Row row) -> row.getValue(ix); + } + Map fieldTypes = referencedFieldTypes(expression, inputSchema); + return compileExpressionFunction(expression, inputSchema, fieldTypes); + } + private static FunctionAndType createFunctionFromExpression(String expression, Schema inputSchema) throws StringCompiler.CompileException, ReflectiveOperationException { if (inputSchema.hasField(expression)) { @@ -207,32 +293,10 @@ private static FunctionAndType createFunctionFromExpression(String expression, S return new FunctionAndType( inputSchema.getField(expression).getType(), (Row row) -> row.getValue(ix)); } else { - Map fieldTypes = new HashMap<>(); - for (Schema.Field field : inputSchema.getFields()) { - if (expression.indexOf(field.getName()) != -1) { - fieldTypes.put(field.getName(), typeFromFieldType(field.getType())); - } - } + Map fieldTypes = referencedFieldTypes(expression, inputSchema); Type type = StringCompiler.guessExpressionType(expression, fieldTypes); - StringBuilder source = new StringBuilder(); - source.append("import java.util.function.Function;\n"); - source.append("import " + Row.class.getTypeName() + ";\n"); - source.append("public class Eval implements Function {\n"); - source.append(" public Object apply(Row __row__) {\n"); - for (Map.Entry fieldEntry : fieldTypes.entrySet()) { - source.append( - String.format( - " %s %s = (%s) __row__.getValue(%s);%n", - fieldEntry.getValue().getTypeName(), - fieldEntry.getKey(), - fieldEntry.getValue().getTypeName(), - inputSchema.indexOf(fieldEntry.getKey()))); - } - source.append(" return " + expression + ";\n"); - source.append(" }\n"); - source.append("}\n"); return new FunctionAndType( - type, (Function) StringCompiler.getInstance("Eval", source.toString())); + type, compileExpressionFunction(expression, inputSchema, fieldTypes)); } } @@ -254,16 +318,27 @@ private static FunctionAndType createFuctionFromCallable(String callable) private static FunctionAndType createFunctionFromName(String name, String path) throws ReflectiveOperationException, MalformedURLException { if (path != null && !new File(path).exists()) { - try (ReadableByteChannel inChannel = - FileSystems.open(FileSystems.matchNewResource(path, false))) { - File tmpJar = File.createTempFile("map-to-fields-" + name, ".jar"); - try (FileChannel outChannel = FileChannel.open(tmpJar.toPath(), StandardOpenOption.WRITE)) { - ByteStreams.copy(inChannel, outChannel); - } - path = tmpJar.getPath(); - } catch (IOException exn) { - throw new RuntimeException(exn); - } + final String remotePath = path; + path = + DOWNLOADED_JARS.compute( + remotePath, + (p, existing) -> { + if (existing != null && new File(existing).exists()) { + return existing; + } + try (ReadableByteChannel inChannel = + FileSystems.open(FileSystems.matchNewResource(p, false))) { + File tmpJar = File.createTempFile("map-to-fields-", ".jar"); + tmpJar.deleteOnExit(); + try (FileChannel outChannel = + FileChannel.open(tmpJar.toPath(), StandardOpenOption.WRITE)) { + ByteStreams.copy(inChannel, outChannel); + } + return tmpJar.getPath(); + } catch (IOException exn) { + throw new RuntimeException(exn); + } + }); } ClassLoader classLoader = path == null @@ -286,19 +361,33 @@ private static FunctionAndType createFunctionFromName(String name, String path) } else { Class clazz = classLoader.loadClass(className); Method method = clazz.getMethod(methodName, Row.class); - Object base = - Modifier.isStatic(method.getModifiers()) - ? null - : clazz.getDeclaredConstructor().newInstance(); - return new FunctionAndType( - method.getGenericReturnType(), - (Row row) -> { - try { - return method.invoke(base, row); - } catch (IllegalAccessException | InvocationTargetException exn) { - throw new RuntimeException(exn); - } - }); + boolean isStatic = Modifier.isStatic(method.getModifiers()); + Object base = isStatic ? null : clazz.getDeclaredConstructor().newInstance(); + Function fn; + try { + MethodHandle rawHandle = MethodHandles.lookup().unreflect(method); + MethodHandle boundHandle = isStatic ? rawHandle : rawHandle.bindTo(base); + fn = + (Row row) -> { + try { + return boundHandle.invoke(row); + } catch (RuntimeException | Error e) { + throw e; + } catch (Throwable exn) { + throw new RuntimeException(exn); + } + }; + } catch (IllegalAccessException e) { + fn = + (Row row) -> { + try { + return method.invoke(base, row); + } catch (ReflectiveOperationException exn) { + throw new RuntimeException(exn); + } + }; + } + return new FunctionAndType(method.getGenericReturnType(), fn); } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/LoggingTransformProvider.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/LoggingTransformProvider.java index 13f7de64700e..cee0644b0932 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/LoggingTransformProvider.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/LoggingTransformProvider.java @@ -19,7 +19,6 @@ import com.google.auto.service.AutoService; import com.google.auto.value.AutoValue; -import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; @@ -162,23 +161,26 @@ public PCollectionRowTuple expand(PCollectionRowTuple input) { } private static DoFn createDoFn(Level logLevel, String prefix, Schema rowSchema) { - SerializableFunction fn = JsonUtils.getRowToJsonBytesFunction(rowSchema); + SerializableFunction fn = JsonUtils.getRowToJsonStringsFunction(rowSchema); return new DoFn() { @ProcessElement public void processElement(@Element Row row, OutputReceiver out) { - String msg = prefix + new String(fn.apply(row), StandardCharsets.UTF_8); - // Looks like this is the best we can do. - // https://stackoverflow.com/questions/2621701/setting-log-level-of-message-at-runtime-in-slf4j switch (logLevel) { case DEBUG: - LOG.debug("{}", msg); + if (LOG.isDebugEnabled()) { + LOG.debug("{}{}", prefix, fn.apply(row)); + } break; case INFO: - LOG.info("{}", msg); + if (LOG.isInfoEnabled()) { + LOG.info("{}{}", prefix, fn.apply(row)); + } break; case ERROR: default: - LOG.error("{}", msg); + if (LOG.isErrorEnabled()) { + LOG.error("{}{}", prefix, fn.apply(row)); + } } out.output(row); } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/StringCompiler.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/StringCompiler.java index 04730dce80c0..082b20b89406 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/StringCompiler.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/StringCompiler.java @@ -50,6 +50,8 @@ import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.Cache; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheBuilder; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; public class StringCompiler { @@ -98,26 +100,42 @@ public DiagnosticCollector getDiagnostics() { } } + private static final Cache> COMPILED_CLASS_CACHE = + CacheBuilder.newBuilder().maximumSize(256).build(); + // TODO(XXX): swap args? + @SuppressWarnings("unchecked") public static Class getClass(String name, String source) throws CompileException, ClassNotFoundException { + String cacheKey = name + '\0' + source; + Class cached = COMPILED_CLASS_CACHE.getIfPresent(cacheKey); + if (cached != null) { + return (Class) cached; + } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - InMemoryFileManager fileManager = - new InMemoryFileManager(compiler.getStandardFileManager(null, null, null)); - DiagnosticCollector diagnostics = new DiagnosticCollector<>(); - JavaCompiler.CompilationTask task = - compiler.getTask( - null, - fileManager, - diagnostics, - ImmutableList.of("-classpath", classpathSupplier.get()), - null, - Collections.singletonList(new InMemoryFileManager.InputJavaFileObject(name, source))); - boolean result = task.call(); - if (!result) { - throw new CompileException(diagnostics); - } else { - return (Class) fileManager.getClassLoader().loadClass(name); + try (InMemoryFileManager fileManager = + new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) { + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + JavaCompiler.CompilationTask task = + compiler.getTask( + null, + fileManager, + diagnostics, + ImmutableList.of("-classpath", classpathSupplier.get()), + null, + Collections.singletonList(new InMemoryFileManager.InputJavaFileObject(name, source))); + boolean result = task.call(); + if (!result) { + throw new CompileException(diagnostics); + } else { + Class loaded = fileManager.getClassLoader().loadClass(name); + if (!"__TypeGuesserHelper__".equals(name)) { + COMPILED_CLASS_CACHE.put(cacheKey, loaded); + } + return (Class) loaded; + } + } catch (IOException e) { + throw new RuntimeException("Failed to close in-memory compiler file manager", e); } } @@ -204,21 +222,29 @@ public JavaFileObject getJavaFileForOutput( } public ClassLoader getClassLoader() { + Map classBytesByName = new HashMap<>(outputFileObjects.size()); + for (Map.Entry entry : outputFileObjects.entrySet()) { + classBytesByName.put(entry.getKey(), entry.getValue().getBytes()); + } return AccessController.doPrivileged( - (PrivilegedAction) - () -> - new SecureClassLoader() { - @Override - protected Class findClass(String name) throws ClassNotFoundException { - OutputJavaFileObject fileObject = outputFileObjects.get(name); - if (fileObject == null) { - throw new ClassNotFoundException(name); - } else { - byte[] classBytes = fileObject.getBytes(); - return defineClass(name, classBytes, 0, classBytes.length); - } - } - }); + (PrivilegedAction) () -> new ByteMapClassLoader(classBytesByName)); + } + + private static final class ByteMapClassLoader extends SecureClassLoader { + private final Map classBytesByName; + + ByteMapClassLoader(Map classBytesByName) { + this.classBytesByName = classBytesByName; + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + byte[] classBytes = classBytesByName.get(name); + if (classBytes == null) { + throw new ClassNotFoundException(name); + } + return defineClass(name, classBytes, 0, classBytes.length); + } } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JsonUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JsonUtils.java index 18f5813c6cc9..c640890184f3 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JsonUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/JsonUtils.java @@ -18,6 +18,9 @@ package org.apache.beam.sdk.schemas.utils; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -29,6 +32,7 @@ import org.apache.beam.sdk.util.RowJson; import org.apache.beam.sdk.util.RowJsonUtils; import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; import org.everit.json.schema.ArraySchema; import org.everit.json.schema.BooleanSchema; import org.everit.json.schema.NumberSchema; @@ -89,13 +93,17 @@ */ public class JsonUtils { - /** Returns a {@link SimpleFunction} mapping JSON byte[] arrays to Beam {@link Row}s. */ + /** + * Returns a {@link SimpleFunction} mapping UTF-8 JSON byte[] arrays to Beam {@link Row}s. + * + *

Input bytes are parsed directly as strict RFC 8259 UTF-8; malformed UTF-8 sequences fail + * with {@link org.apache.beam.sdk.util.RowJson.UnsupportedRowJsonException}. + */ public static SimpleFunction getJsonBytesToRowFunction(Schema beamSchema) { return new JsonToRowFn(beamSchema) { @Override public Row apply(byte[] input) { - String jsonString = byteArrayToJsonString(input); - return RowJsonUtils.jsonToRow(objectMapper, jsonString); + return RowJsonUtils.jsonBytesToRow(getReader(), input); } }; } @@ -105,7 +113,7 @@ public static SimpleFunction getJsonStringToRowFunction(Schema beam return new JsonToRowFn(beamSchema) { @Override public Row apply(String jsonString) { - return RowJsonUtils.jsonToRow(objectMapper, jsonString); + return RowJsonUtils.jsonToRow(getReader(), jsonString); } }; } @@ -115,8 +123,7 @@ public static SimpleFunction getRowToJsonBytesFunction(Schema beamS return new RowToJsonFn(beamSchema) { @Override public byte[] apply(Row input) { - String jsonString = RowJsonUtils.rowToJson(objectMapper, input); - return jsonStringToByteArray(jsonString); + return RowJsonUtils.rowToJsonBytes(getWriter(), input); } }; } @@ -126,7 +133,7 @@ public static SimpleFunction getRowToJsonStringsFunction(Schema bea return new RowToJsonFn(beamSchema) { @Override public String apply(Row input) { - return RowJsonUtils.rowToJson(objectMapper, input); + return RowJsonUtils.rowToJson(getWriter(), input); } }; } @@ -320,21 +327,45 @@ private static org.everit.json.schema.ObjectSchema jsonSchemaFromString(String j private abstract static class JsonToRowFn extends SimpleFunction { final RowJson.RowJsonDeserializer deserializer; - final ObjectMapper objectMapper; + + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") + private transient volatile @Nullable ObjectReader objectReader; private JsonToRowFn(Schema beamSchema) { - deserializer = RowJson.RowJsonDeserializer.forSchema(beamSchema); - objectMapper = RowJsonUtils.newObjectMapperWith(deserializer); + this.deserializer = RowJson.RowJsonDeserializer.forSchema(beamSchema); + ObjectMapper mapper = RowJsonUtils.newObjectMapperWith(this.deserializer); + this.objectReader = mapper.readerFor(Row.class); + } + + final ObjectReader getReader() { + ObjectReader reader = objectReader; + if (reader == null) { + reader = RowJsonUtils.newObjectMapperWith(deserializer).readerFor(Row.class); + objectReader = reader; + } + return reader; } } private abstract static class RowToJsonFn extends SimpleFunction { final RowJson.RowJsonSerializer serializer; - final ObjectMapper objectMapper; + + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") + private transient volatile @Nullable ObjectWriter objectWriter; private RowToJsonFn(Schema beamSchema) { - serializer = RowJson.RowJsonSerializer.forSchema(beamSchema); - objectMapper = RowJsonUtils.newObjectMapperWith(serializer); + this.serializer = RowJson.RowJsonSerializer.forSchema(beamSchema); + ObjectMapper mapper = RowJsonUtils.newObjectMapperWith(this.serializer); + this.objectWriter = mapper.writerFor(Row.class); + } + + final ObjectWriter getWriter() { + ObjectWriter writer = objectWriter; + if (writer == null) { + writer = RowJsonUtils.newObjectMapperWith(serializer).writerFor(Row.class); + objectWriter = writer; + } + return writer; } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/RowJsonUtils.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/RowJsonUtils.java index ee41d0da28fe..c4f1a27377bf 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/RowJsonUtils.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/RowJsonUtils.java @@ -22,8 +22,11 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; +import java.nio.charset.StandardCharsets; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.util.RowJson.UnsupportedRowJsonException; import org.apache.beam.sdk.values.Row; @@ -141,6 +144,31 @@ public static Row jsonToRow(ObjectMapper objectMapper, String jsonString) { } } + public static Row jsonToRow(ObjectReader objectReader, String jsonString) { + try { + return objectReader.readValue(jsonString); + } catch (JsonParseException | JsonMappingException jsonException) { + throw new UnsupportedRowJsonException("Unable to parse Row", jsonException); + } catch (IOException e) { + throw new IllegalArgumentException("Unable to parse json object: " + jsonString, e); + } + } + + /** + * Parses UTF-8 JSON bytes into a {@link Row} using {@code objectReader}. Enforces strict RFC 8259 + * UTF-8 validation (malformed UTF-8 byte sequences raise {@link UnsupportedRowJsonException}). + */ + public static Row jsonBytesToRow(ObjectReader objectReader, byte[] jsonBytes) { + try { + return objectReader.readValue(jsonBytes); + } catch (JsonParseException | JsonMappingException jsonException) { + throw new UnsupportedRowJsonException("Unable to parse Row", jsonException); + } catch (IOException e) { + throw new IllegalArgumentException( + "Unable to parse json object: " + new String(jsonBytes, StandardCharsets.UTF_8), e); + } + } + public static String rowToJson(ObjectMapper objectMapper, Row row) { try { return objectMapper.writeValueAsString(row); @@ -148,4 +176,20 @@ public static String rowToJson(ObjectMapper objectMapper, Row row) { throw new IllegalArgumentException("Unable to serialize row: " + row, e); } } + + public static String rowToJson(ObjectWriter objectWriter, Row row) { + try { + return objectWriter.writeValueAsString(row); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("Unable to serialize row: " + row, e); + } + } + + public static byte[] rowToJsonBytes(ObjectWriter objectWriter, Row row) { + try { + return objectWriter.writeValueAsBytes(row); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("Unable to serialize row: " + row, e); + } + } } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProviderTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProviderTest.java index 6ad6f353a4dd..440d1d3a9af8 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProviderTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/providers/JavaMapToFieldsTransformProviderTest.java @@ -189,4 +189,71 @@ public void testErrorHandling() { .build()); pipeline.run(); } + + @Test + @Category(NeedsRunner.class) + public void testErrorHandlingRoutesInvalidCompositeUdfOutputToErrors() { + Schema inputSchema = Schema.of(Schema.Field.of("x", Schema.FieldType.INT32)); + + PCollection input = + pipeline + .apply( + Create.of( + Row.withSchema(inputSchema).addValues(1).build(), + Row.withSchema(inputSchema).addValues(-1).build())) + .setRowSchema(inputSchema); + + PCollectionRowTuple result = + PCollectionRowTuple.of(JavaMapToFieldsTransformProvider.INPUT_ROWS_TAG, input) + .apply( + new JavaMapToFieldsTransformProvider() + .from( + JavaMapToFieldsTransformProvider.Configuration.builder() + .setLanguage("java") + .setFields( + ImmutableMap.of( + "nums", + JavaRowUdf.Configuration.builder() + .setCallable( + "import java.util.Collections;" + + "import java.util.List;" + + "import java.util.function.Function;" + + "import org.apache.beam.sdk.values.Row;" + + "public class MaybeBadList implements Function> {" + + " @SuppressWarnings({\"unchecked\", \"rawtypes\"})" + + " public List apply(Row row) {" + + " int x = row.getInt32(\"x\");" + + " if (x < 0) {" + + " return (List) Collections.singletonList(\"not-an-int\");" + + " }" + + " return Collections.singletonList(x);" + + " }" + + "}") + .build())) + .setErrorHandling(ErrorHandling.builder().setOutput("errors").build()) + .build())); + + PCollection ok = result.get(JavaMapToFieldsTransformProvider.OUTPUT_ROWS_TAG); + Schema outputSchema = ok.getSchema(); + PAssert.that(ok) + .containsInAnyOrder( + Row.withSchema(outputSchema) + .withFieldValue("nums", java.util.Collections.singletonList(1)) + .build()); + + PCollection errors = result.get("errors"); + PAssert.that(errors) + .satisfies( + rows -> { + int count = 0; + for (Row r : rows) { + count++; + org.junit.Assert.assertEquals( + Row.withSchema(inputSchema).addValues(-1).build(), r.getRow("failed_row")); + } + org.junit.Assert.assertEquals(1, count); + return null; + }); + pipeline.run(); + } } From 75b71a2f4016e96ec32fc371c0ec41e5a689e062 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:58:57 -0800 Subject: [PATCH 12/15] Optimize Avro schema conversion and logical-type utilities Eliminates eager String.format allocations in checkRawType, caches toAvroSchema conversions, shares a static DecimalConversion instance, avoids stream/filter allocations on nullable unions, and fast-paths numeric/timestamp conversions. --- .../utils/AvroJodaTimeConversions.java | 4 +- .../avro/schemas/utils/AvroUtils.java | 186 ++++++++++++------ 2 files changed, 124 insertions(+), 66 deletions(-) diff --git a/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroJodaTimeConversions.java b/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroJodaTimeConversions.java index 68b61b189959..658d174bef84 100644 --- a/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroJodaTimeConversions.java +++ b/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroJodaTimeConversions.java @@ -78,7 +78,7 @@ public LocalTime fromInt(Integer millisFromMidnight, Schema schema, LogicalType @Override public Integer toInt(LocalTime time, Schema schema, LogicalType type) { - return time.millisOfDay().get(); + return time.getMillisOfDay(); } } @@ -102,7 +102,7 @@ public LocalTime fromLong(Long microsFromMidnight, Schema schema, LogicalType ty public static class LossyTimeMicrosConversion extends TimeMicrosConversion { @Override public Long toLong(LocalTime time, Schema schema, LogicalType type) { - return 1000 * (long) time.millisOfDay().get(); + return 1000L * time.getMillisOfDay(); } } diff --git a/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroUtils.java b/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroUtils.java index 302c524722ae..ec98427f83d2 100644 --- a/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroUtils.java +++ b/sdks/java/extensions/avro/src/main/java/org/apache/beam/sdk/extensions/avro/schemas/utils/AvroUtils.java @@ -31,14 +31,13 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; -import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nonnull; import net.bytebuddy.description.type.TypeDescription.ForLoadedType; @@ -100,8 +99,6 @@ import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TypeDescriptor; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.CaseFormat; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; import org.apache.commons.lang3.reflect.FieldUtils; @@ -246,17 +243,38 @@ public static TypeWithNullability create(org.apache.avro.Schema avroSchema) { TypeWithNullability(org.apache.avro.Schema avroSchema) { if (avroSchema.getType() == org.apache.avro.Schema.Type.UNION) { List types = avroSchema.getTypes(); + int size = types.size(); + // Fast path for the common 2-branch nullable Avro union: ["null", T] or [T, "null"]. + if (size == 2) { + org.apache.avro.Schema first = types.get(0); + org.apache.avro.Schema second = types.get(1); + boolean firstNull = first.getType() == org.apache.avro.Schema.Type.NULL; + boolean secondNull = second.getType() == org.apache.avro.Schema.Type.NULL; + if (firstNull && !secondNull) { + type = second; + nullable = true; + return; + } else if (secondNull && !firstNull) { + type = first; + nullable = true; + return; + } else { + type = avroSchema; + nullable = false; + return; + } + } - // optional fields in AVRO have form of: - // {"name": "foo", "type": ["null", "something"]} - - // don't need recursion because nested unions aren't supported in AVRO - List nonNullTypes = - types.stream() - .filter(x -> x.getType() != org.apache.avro.Schema.Type.NULL) - .collect(Collectors.toList()); + // General path for 0/1/3+ branch unions without allocating a stream pipeline. + List nonNullTypes = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + org.apache.avro.Schema branch = types.get(i); + if (branch.getType() != org.apache.avro.Schema.Type.NULL) { + nonNullTypes.add(branch); + } + } - if (nonNullTypes.size() == types.size() || nonNullTypes.isEmpty()) { + if (nonNullTypes.size() == size || nonNullTypes.isEmpty()) { // union without `null` or all 'null' union, keep as is. type = avroSchema; nullable = false; @@ -814,15 +832,39 @@ public static SerializableFunction getRowToGenericRecordFunc } private static class RowToGenericRecordFn implements SerializableFunction { + private static final class CachedAvroSchema { + final Schema beamSchema; + final org.apache.avro.Schema avroSchema; + + CachedAvroSchema(Schema beamSchema, org.apache.avro.Schema avroSchema) { + this.beamSchema = beamSchema; + this.avroSchema = avroSchema; + } + } + private transient org.apache.avro.@Nullable Schema avroSchema; + private transient volatile @Nullable CachedAvroSchema cachedInferred; RowToGenericRecordFn(org.apache.avro.@Nullable Schema avroSchema) { this.avroSchema = avroSchema; } @Override + @SuppressWarnings("ReferenceEquality") public GenericRecord apply(Row input) { - return toGenericRecord(input, avroSchema); + org.apache.avro.Schema targetSchema = avroSchema; + if (targetSchema == null) { + Schema beamSchema = input.getSchema(); + CachedAvroSchema cached = cachedInferred; + if (cached != null + && (cached.beamSchema == beamSchema || cached.beamSchema.equals(beamSchema))) { + targetSchema = cached.avroSchema; + } else { + targetSchema = toAvroSchema(beamSchema); + cachedInferred = new CachedAvroSchema(beamSchema, targetSchema); + } + } + return toGenericRecord(input, targetSchema); } @Override @@ -1272,16 +1314,10 @@ private static org.apache.avro.Schema getFieldSchema( return fieldType.getNullable() ? ReflectData.makeNullable(baseType) : baseType; } - private static final Map> - NUMERIC_CONVERTERS = - ImmutableMap.of( - org.apache.avro.Schema.create(org.apache.avro.Schema.Type.INT), Number::intValue, - org.apache.avro.Schema.create(org.apache.avro.Schema.Type.LONG), Number::longValue, - org.apache.avro.Schema.create(org.apache.avro.Schema.Type.FLOAT), Number::floatValue, - org.apache.avro.Schema.create(org.apache.avro.Schema.Type.DOUBLE), - Number::doubleValue); + private static final Conversions.DecimalConversion DECIMAL_CONVERSION = + new Conversions.DecimalConversion(); - /** Convert a value from Beam Row to a vlue used for Avro GenericRecord. */ + /** Convert a value from Beam Row to a value used for Avro GenericRecord. */ private static @Nullable Object genericFromBeamField( FieldType fieldType, org.apache.avro.Schema avroSchema, @Nullable Object value) { TypeWithNullability typeWithNullability = new TypeWithNullability(avroSchema); @@ -1298,8 +1334,20 @@ private static org.apache.avro.Schema getFieldSchema( return value; } - if (NUMERIC_CONVERTERS.containsKey(typeWithNullability.type)) { - return NUMERIC_CONVERTERS.get(typeWithNullability.type).apply((Number) value); + org.apache.avro.Schema unwrapped = typeWithNullability.type; + if (unwrapped.getLogicalType() == null && unwrapped.getObjectProps().isEmpty()) { + switch (unwrapped.getType()) { + case INT: + return value instanceof Integer ? value : ((Number) value).intValue(); + case LONG: + return value instanceof Long ? value : ((Number) value).longValue(); + case FLOAT: + return value instanceof Float ? value : ((Number) value).floatValue(); + case DOUBLE: + return value instanceof Double ? value : ((Number) value).doubleValue(); + default: + break; + } } // TODO: should we use Avro Schema as the source-of-truth in general? @@ -1320,7 +1368,7 @@ private static org.apache.avro.Schema getFieldSchema( BigDecimal decimal = (BigDecimal) value; LogicalType logicalType = typeWithNullability.type.getLogicalType(); @SuppressWarnings("nullness") - ByteBuffer result = new Conversions.DecimalConversion().toBytes(decimal, null, logicalType); + ByteBuffer result = DECIMAL_CONVERSION.toBytes(decimal, null, logicalType); return result; case DATETIME: @@ -1394,11 +1442,15 @@ private static org.apache.avro.Schema getFieldSchema( + TimeUnit.NANOSECONDS.toMicros(instant.getNano()); } else if (Timestamp.IDENTIFIER.equals(identifier)) { java.time.Instant instant = (java.time.Instant) value; - // Use BigInteger to work around long overflows so that epochNanos = Long.MIN_VALUE can be - // supported. Instant always stores nanos as positive adjustment so the math will silently - // overflow with regular int64. - BigInteger epochSeconds = BigInteger.valueOf(instant.getEpochSecond()); - BigInteger nanosOfSecond = BigInteger.valueOf(instant.getNano()); + long secs = instant.getEpochSecond(); + int nanos = instant.getNano(); + // Fast path covering year ~1678 to ~2262 without BigInteger allocation. + if (secs > -9_223_372_036L && secs < 9_223_372_036L) { + return secs * 1_000_000_000L + nanos; + } + // Boundary fallback so epochNanos == Long.MIN_VALUE stays exact and overflows throw. + BigInteger epochSeconds = BigInteger.valueOf(secs); + BigInteger nanosOfSecond = BigInteger.valueOf(nanos); BigInteger epochNanos = epochSeconds.multiply(BigInteger.valueOf(1_000_000_000L)).add(nanosOfSecond); return epochNanos.longValueExact(); @@ -1410,7 +1462,9 @@ private static org.apache.avro.Schema getFieldSchema( case ITERABLE: Iterable iterable = (Iterable) value; List<@Nullable Object> translatedArray = - Lists.newArrayListWithExpectedSize(Iterables.size(iterable)); + iterable instanceof Collection + ? new ArrayList<>(((Collection) iterable).size()) + : new ArrayList<>(); for (Object arrayElement : iterable) { translatedArray.add( @@ -1422,8 +1476,8 @@ private static org.apache.avro.Schema getFieldSchema( return translatedArray; case MAP: - Map map = Maps.newHashMap(); Map valueMap = (Map) value; + Map map = Maps.newHashMapWithExpectedSize(valueMap.size()); for (Map.Entry entry : valueMap.entrySet()) { Utf8 key = new Utf8((String) checkNotNull(entry.getKey())); map.put( @@ -1445,10 +1499,9 @@ private static org.apache.avro.Schema getFieldSchema( private static @Nullable Object convertLogicalType( @Nonnull Object value, - @Nonnull org.apache.avro.Schema avroSchema, + @Nonnull TypeWithNullability type, @Nonnull FieldType fieldType, @Nonnull GenericData genericData) { - TypeWithNullability type = new TypeWithNullability(avroSchema); // TODO: Remove this workaround once Avro is upgraded to 1.12+ where timestamp-nanos if (TIMESTAMP_NANOS_LOGICAL_TYPE.equals(type.type.getProp("logicalType"))) { @@ -1514,9 +1567,8 @@ private static org.apache.avro.Schema getFieldSchema( ByteBuffer byteBuffer = checkRawType( ByteBuffer.class, value, logicalType, rawType, conversion, convertedType); - Conversion decimalConversion = new Conversions.DecimalConversion(); BigDecimal bigDecimal = - decimalConversion.fromBytes(byteBuffer.duplicate(), type.type, logicalType); + DECIMAL_CONVERSION.fromBytes(byteBuffer.duplicate(), type.type, logicalType); return convertDecimal(bigDecimal, fieldType); } case "uuid": @@ -1544,14 +1596,13 @@ private static org.apache.avro.Schema getFieldSchema( if (value == null) { return null; } - Object convertedLogicalType = convertLogicalType(value, avroSchema, fieldType, genericData); + TypeWithNullability type = new TypeWithNullability(avroSchema); + Object convertedLogicalType = convertLogicalType(value, type, fieldType, genericData); if (convertedLogicalType != null) { return convertedLogicalType; } - TypeWithNullability type = new TypeWithNullability(avroSchema); - switch (type.type.getType()) { case FIXED: return convertFixedStrict((GenericFixed) value, fieldType); @@ -1746,7 +1797,7 @@ private static Object convertMapStrict( "Can't convert 'string' map keys to " + fieldType.getMapKeyType()); } - Map ret = new HashMap<>(); + Map ret = Maps.newHashMapWithExpectedSize(values.size()); for (Map.Entry value : values.entrySet()) { ret.put( @@ -1776,17 +1827,25 @@ private static org.apache.avro.Schema buildHiveLogicalTypeSchema( return new org.apache.avro.Schema.Parser().parse(schemaJson); } + private static final ClassValue SPECIFIC_MODEL_CACHE = + new ClassValue() { + @Override + protected GenericData computeValue(Class type) { + try { + return (GenericData) FieldUtils.readStaticField(type, "MODEL$", true); + } catch (IllegalAccessException ex) { + throw new IllegalArgumentException( + "Unable to access MODEL$ field in SpecificRecordBase class", ex); + } + } + }; + static GenericData getGenericData(SpecificRecordBase record) { try { return record.getSpecificData(); } catch (NoSuchMethodError e) { - try { - // SpecificRecordBase.getSpecificData() was not available in avro 182 - return (GenericData) FieldUtils.readStaticField(record.getClass(), "MODEL$", true); - } catch (IllegalAccessException ex) { - throw new IllegalArgumentException( - "Unable to access MODEL$ field in SpecificRecordBase class", ex); - } + // SpecificRecordBase.getSpecificData() was not available in Avro 1.8.2. + return SPECIFIC_MODEL_CACHE.get(record.getClass()); } } @@ -1797,23 +1856,22 @@ private static T checkRawType( Object rawType, @Nullable Conversion conversion, @Nullable Class convertedType) { - String msg = - String.format( - "Value %s of class %s is not a supported type for logical type %s (%s). " - + "Underlying avro built-in raw type should be instance of %s. " - + "However it is instance of %s and has value %s ." - + "Generic data has conversion %s, convertedType %s", - value, - value.getClass(), - logicalType.getName(), - logicalType, - desiredRawType, - rawType.getClass(), - rawType, - conversion, - convertedType); if (!desiredRawType.isInstance(rawType)) { - throw new IllegalArgumentException(msg); + throw new IllegalArgumentException( + String.format( + "Value %s of class %s is not a supported type for logical type %s (%s). " + + "Underlying avro built-in raw type should be instance of %s. " + + "However it is instance of %s and has value %s ." + + "Generic data has conversion %s, convertedType %s", + value, + value.getClass(), + logicalType.getName(), + logicalType, + desiredRawType, + rawType.getClass(), + rawType, + conversion, + convertedType)); } return (T) rawType; } From 20b2b9078b4a1c098ea468c2acc8ea135a80f499 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:59:16 -0800 Subject: [PATCH 13/15] Optimize Protobuf coders and schema utilities Caches volatile Protobuf parsers and uses getSerializedSize() in ProtoCoder/DynamicProtoCoder, caches descriptors and OneOf/builder creators in ProtoByteUtils/ProtoByteBuddyUtils, fast-paths matching schemas in ProtoPayloadSerializerProvider, and uses Row.attachValues in ProtoSchemaLogicalTypes. --- .../protobuf/DynamicProtoCoder.java | 18 ++- .../protobuf/ProtoByteBuddyUtils.java | 53 +++++--- .../extensions/protobuf/ProtoByteUtils.java | 61 ++++++--- .../sdk/extensions/protobuf/ProtoCoder.java | 74 +++++++---- .../ProtoPayloadSerializerProvider.java | 8 +- .../protobuf/ProtoSchemaLogicalTypes.java | 4 +- .../protobuf/ProtoSchemaTranslator.java | 116 ++++++++++-------- 7 files changed, 209 insertions(+), 125 deletions(-) diff --git a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/DynamicProtoCoder.java b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/DynamicProtoCoder.java index 9a9af74e48a1..ac8885d70ead 100644 --- a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/DynamicProtoCoder.java +++ b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/DynamicProtoCoder.java @@ -153,13 +153,19 @@ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IO /** Get the memoized {@link Parser}, possibly initializing it lazily. */ @Override - protected synchronized Parser getParser() { - if (memoizedParser == null) { - DynamicMessage protoMessageInstance = - DynamicMessage.newBuilder(domain.getDescriptor(messageName)).build(); - memoizedParser = protoMessageInstance.getParserForType(); + protected Parser getParser() { + Parser parser = memoizedParser; + if (parser == null) { + synchronized (this) { + parser = memoizedParser; + if (parser == null) { + DynamicMessage protoMessageInstance = + DynamicMessage.newBuilder(domain.getDescriptor(messageName)).build(); + memoizedParser = parser = protoMessageInstance.getParserForType(); + } + } } - return memoizedParser; + return parser; } /** diff --git a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteBuddyUtils.java b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteBuddyUtils.java index a1e45868e87d..b4de7250e1ec 100644 --- a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteBuddyUtils.java +++ b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteBuddyUtils.java @@ -476,11 +476,11 @@ public TypeConversion createSetterConversions(StackManipulati Schema schema, FieldValueTypeSupplier fieldValueTypeSupplier, TypeConversionsFactory typeConversionsFactory) { - Multimap methods = ReflectUtils.getMethodsMap(clazz); return (List) CACHED_GETTERS.computeIfAbsent( ClassWithSchema.create(clazz, schema), c -> { + Multimap methods = ReflectUtils.getMethodsMap(clazz); List types = fieldValueTypeSupplier.get(TypeDescriptor.of(clazz), schema); return types.stream() @@ -630,9 +630,11 @@ private static boolean isContiguous(Set indices) { Preconditions.checkArgument(iter.hasNext()); int current = iter.next(); while (iter.hasNext()) { - if (iter.next() > current + 1) { + int next = iter.next(); + if (next != current + 1) { return false; } + current = next; } return true; } @@ -780,13 +782,10 @@ public ByteCodeAppender appender(final Target implementationTarget) { // Start the switch block. if (isContiguous) { - // If the case enum values are not all contiguous (i.e. there are holes), then generate - // the slower - // TABLESWITCH opcode. + // Contiguous case numbers allow the O(1) TABLESWITCH opcode. methodVisitor.visitTableSwitchInsn(keys[0], keys[keys.length - 1], defaultLabel, labels); } else { - // If all the case enum value are contiguous, then generate the faster LOOKUPSWITCH - // opcode. + // Sparse case numbers with holes require LOOKUPSWITCH. methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, labels); } @@ -914,12 +913,10 @@ public ByteCodeAppender appender(final Target implementationTarget) { // Start the switch block. if (isContiguous) { - // If the case enum values are not all contiguous (i.e. there are holes), then generate - // the slower TABLESWITCH opcode. + // Contiguous case numbers allow the O(1) TABLESWITCH opcode. methodVisitor.visitTableSwitchInsn(keys[0], keys[keys.length - 1], defaultLabel, labels); } else { - // If all the case enum value are contiguous, then generate the faster LOOKUPSWITCH - // opcode. + // Sparse case numbers with holes require LOOKUPSWITCH. methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, labels); } @@ -1070,21 +1067,41 @@ static Method getProtoGetter(Multimap methods, String name, Fiel .orElse(null); } + // Anchor proto builder creators to the proto message class via ClassValue so user ClassLoaders + // are never pinned by static maps. + private static final ClassValue> CACHED_BUILDER_CREATORS = + new ClassValue>() { + @Override + protected Map computeValue(Class type) { + return Maps.newConcurrentMap(); + } + }; + public static @Nullable SchemaUserTypeCreator getBuilderCreator( TypeDescriptor protoTypeDescriptor, Schema schema, FieldValueTypeSupplier fieldValueTypeSupplier) { - Class builderClass = getProtoGeneratedBuilder(protoTypeDescriptor.getRawType()); + Class rawType = protoTypeDescriptor.getRawType(); + Map perClassCache = CACHED_BUILDER_CREATORS.get(rawType); + SchemaUserTypeCreator cached = perClassCache.get(schema); + if (cached != null) { + return cached; + } + Class builderClass = getProtoGeneratedBuilder(rawType); if (builderClass == null) { return null; } - Multimap methods = ReflectUtils.getMethodsMap(builderClass); - List> setters = - schema.getFields().stream() - .map(f -> getProtoFieldValueSetter(protoTypeDescriptor, f, methods, builderClass)) - .collect(Collectors.toList()); - return createBuilderCreator(protoTypeDescriptor.getRawType(), builderClass, setters, schema); + return perClassCache.computeIfAbsent( + schema, + s -> { + Multimap methods = ReflectUtils.getMethodsMap(builderClass); + List> setters = + s.getFields().stream() + .map(f -> getProtoFieldValueSetter(protoTypeDescriptor, f, methods, builderClass)) + .collect(Collectors.toList()); + return createBuilderCreator(rawType, builderClass, setters, s); + }); } private static diff --git a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteUtils.java b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteUtils.java index 2e8937e7a271..bcb61ab70255 100644 --- a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteUtils.java +++ b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoByteUtils.java @@ -47,6 +47,7 @@ import org.apache.beam.sdk.values.Row; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter; import org.apache.commons.compress.utils.IOUtils; +import org.checkerframework.checker.nullness.qual.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -122,19 +123,30 @@ private static Descriptors.Descriptor getDescriptorFromProtoSchema( public static SerializableFunction getProtoBytesToRowFromSchemaFunction( String schemaString, String messageName) { - Descriptors.Descriptor descriptor = getDescriptorFromProtoSchema(schemaString, messageName); + Descriptors.Descriptor initialDescriptor = + getDescriptorFromProtoSchema(schemaString, messageName); ProtoDynamicMessageSchema protoDynamicMessageSchema = - ProtoDynamicMessageSchema.forDescriptor(ProtoDomain.buildFrom(descriptor), descriptor); + ProtoDynamicMessageSchema.forDescriptor( + ProtoDomain.buildFrom(initialDescriptor), initialDescriptor); return new SimpleFunction() { + private transient volatile Descriptors.@Nullable Descriptor cachedDescriptor; + private transient volatile @Nullable SerializableFunction cachedToRow; + @Override public Row apply(byte[] input) { try { - Descriptors.Descriptor descriptorFunction = - getDescriptorFromProtoSchema(schemaString, messageName); - DynamicMessage dynamicMessage = DynamicMessage.parseFrom(descriptorFunction, input); - SerializableFunction res = - protoDynamicMessageSchema.getToRowFunction(); + Descriptors.Descriptor descriptor = cachedDescriptor; + if (descriptor == null) { + descriptor = getDescriptorFromProtoSchema(schemaString, messageName); + cachedDescriptor = descriptor; + } + DynamicMessage dynamicMessage = DynamicMessage.parseFrom(descriptor, input); + SerializableFunction res = cachedToRow; + if (res == null) { + res = protoDynamicMessageSchema.getToRowFunction(); + cachedToRow = res; + } return res.apply(dynamicMessage); } catch (InvalidProtocolBufferException e) { LOG.error("Error parsing to DynamicMessage", e); @@ -152,19 +164,29 @@ public static SerializableFunction getProtoBytesToRowFunction( @SuppressWarnings("unchecked") ProtoDynamicMessageSchema protoDynamicMessageSchema = ProtoDynamicMessageSchema.forDescriptor(protoDomain, messageName); + List messageElements = Splitter.on('.').splitToList(messageName); + final String messageTypeByName = messageElements.get(messageElements.size() - 1); return new SimpleFunction() { + private transient volatile Descriptors.@Nullable Descriptor cachedDescriptor; + private transient volatile @Nullable SerializableFunction cachedToRow; + @Override public Row apply(byte[] input) { try { - List messageElements = Splitter.on('.').splitToList(messageName); - String messageTypeByName = messageElements.get(messageElements.size() - 1); - final Descriptors.Descriptor descriptor = - protoDomain - .getFileDescriptor(dynamicProtoDomain.getFileName()) - .findMessageTypeByName(messageTypeByName); + Descriptors.Descriptor descriptor = cachedDescriptor; + if (descriptor == null) { + descriptor = + protoDomain + .getFileDescriptor(dynamicProtoDomain.getFileName()) + .findMessageTypeByName(messageTypeByName); + cachedDescriptor = descriptor; + } DynamicMessage dynamicMessage = DynamicMessage.parseFrom(descriptor, input); - SerializableFunction res = - protoDynamicMessageSchema.getToRowFunction(); + SerializableFunction res = cachedToRow; + if (res == null) { + res = protoDynamicMessageSchema.getToRowFunction(); + cachedToRow = res; + } return res.apply(dynamicMessage); } catch (InvalidProtocolBufferException e) { LOG.error("Error parsing to DynamicMessage", e); @@ -182,10 +204,15 @@ public static SerializableFunction getRowToProtoBytesFromSchema( ProtoDynamicMessageSchema protoDynamicMessageSchema = ProtoDynamicMessageSchema.forDescriptor(ProtoDomain.buildFrom(descriptor), descriptor); return new SimpleFunction() { + private transient volatile @Nullable SerializableFunction cachedFromRow; + @Override public byte[] apply(Row input) { - SerializableFunction res = - protoDynamicMessageSchema.getFromRowFunction(); + SerializableFunction res = cachedFromRow; + if (res == null) { + res = protoDynamicMessageSchema.getFromRowFunction(); + cachedFromRow = res; + } return res.apply(input).toByteArray(); } }; diff --git a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoCoder.java b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoCoder.java index 012bef005516..14695cbafb5c 100644 --- a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoCoder.java +++ b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoCoder.java @@ -233,6 +233,21 @@ public void verifyDeterministic() throws NonDeterministicException { ProtobufUtil.verifyDeterministic(this); } + @Override + protected long getEncodedElementByteSize(T value) throws Exception { + if (value == null) { + throw new CoderException("cannot encode a null " + protoMessageClass.getSimpleName()); + } + int serializedSize = value.getSerializedSize(); + return (long) com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(serializedSize) + + serializedSize; + } + + @Override + public boolean isRegisterByteSizeObserverCheap(T value) { + return true; + } + /** Returns the Protocol Buffers {@link Message} type this {@link ProtoCoder} supports. */ public Class getMessageType() { return protoMessageClass; @@ -286,7 +301,7 @@ public ExtensionRegistry getExtensionRegistry() { // Transient fields that are lazy initialized and then memoized. private transient volatile ExtensionRegistry memoizedExtensionRegistry; - transient Parser memoizedParser; + transient volatile Parser memoizedParser; /** Private constructor. */ protected ProtoCoder(Class protoMessageClass, Set> extensionHostClasses) { @@ -295,34 +310,41 @@ protected ProtoCoder(Class protoMessageClass, Set> extensionHostClas } /** Get the memoized {@link Parser}, possibly initializing it lazily. */ - protected synchronized Parser getParser() { - if (memoizedParser == null) { - try { - if (DynamicMessage.class.equals(protoMessageClass)) { - throw new IllegalArgumentException( - "DynamicMessage is not supported by the ProtoCoder, use the DynamicProtoCoder."); - } else { - @SuppressWarnings("unchecked") - T protoMessageInstance = - (T) protoMessageClass.getMethod("getDefaultInstance").invoke(null); - @SuppressWarnings("unchecked") - Parser tParser = (Parser) protoMessageInstance.getParserForType(); - memoizedParser = tParser; + protected Parser getParser() { + Parser parser = memoizedParser; + if (parser == null) { + synchronized (this) { + parser = memoizedParser; + if (parser == null) { + try { + if (DynamicMessage.class.equals(protoMessageClass)) { + throw new IllegalArgumentException( + "DynamicMessage is not supported by the ProtoCoder, use the DynamicProtoCoder."); + } else { + @SuppressWarnings("unchecked") + T protoMessageInstance = + (T) protoMessageClass.getMethod("getDefaultInstance").invoke(null); + @SuppressWarnings("unchecked") + Parser tParser = (Parser) protoMessageInstance.getParserForType(); + memoizedParser = parser = tParser; + } + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException( + String.format( + "Cannot decode %s: it has no static getDefaultInstance() method, so its Parser " + + "cannot be determined. This happens for the raw %s interface, e.g. when " + + "the coder was inferred for a generic 'T extends Message'. Use a " + + "concrete generated message class, DynamicProtoCoder, or call " + + "setCoder().", + protoMessageClass.getName(), Message.class.getName()), + e); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new IllegalArgumentException(e); + } } - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException( - String.format( - "Cannot decode %s: it has no static getDefaultInstance() method, so its Parser " - + "cannot be determined. This happens for the raw %s interface, e.g. when the " - + "coder was inferred for a generic 'T extends Message'. Use a concrete " - + "generated message class, DynamicProtoCoder, or call setCoder().", - protoMessageClass.getName(), Message.class.getName()), - e); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new IllegalArgumentException(e); } } - return memoizedParser; + return parser; } /** diff --git a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoPayloadSerializerProvider.java b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoPayloadSerializerProvider.java index 9530e5b24e0d..95464ac33f26 100644 --- a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoPayloadSerializerProvider.java +++ b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoPayloadSerializerProvider.java @@ -50,7 +50,7 @@ private static Class getClass(Map tableParams } } - private static void inferAndVerifySchema( + private static Schema inferAndVerifySchema( Class protoClass, Schema requiredSchema) { @Nonnull Schema inferredSchema = @@ -64,13 +64,17 @@ private static void inferAndVerifySchema( + "Inferred schema: '%s'", requiredSchema, protoClass.getName(), inferredSchema)); } + return inferredSchema; } @Override public PayloadSerializer getSerializer(Schema schema, Map tableParams) { Class protoClass = getClass(tableParams); - inferAndVerifySchema(protoClass, schema); + Schema inferredSchema = inferAndVerifySchema(protoClass, schema); SimpleFunction toRowFn = ProtoMessageSchema.getProtoBytesToRowFn(protoClass); + if (inferredSchema.equals(schema)) { + return PayloadSerializer.of(ProtoMessageSchema.getRowToProtoBytesFn(protoClass), toRowFn); + } return PayloadSerializer.of( ProtoMessageSchema.getRowToProtoBytesFn(protoClass), bytes -> { diff --git a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaLogicalTypes.java b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaLogicalTypes.java index 63e264955b73..1904da457986 100644 --- a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaLogicalTypes.java +++ b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaLogicalTypes.java @@ -39,7 +39,7 @@ public static class TimestampConvert { /** ByteBuddy conversion for Timestamp to NanosInstant base type. */ public static Row toRow(Timestamp input) { - return Row.withSchema(SCHEMA).addValues(input.getSeconds(), input.getNanos()).build(); + return Row.attachValues(SCHEMA, input.getSeconds(), input.getNanos()); } /** ByteBuddy conversion for NanosInstant base type to Timestamp. */ @@ -51,7 +51,7 @@ public static Timestamp toTimestamp(Row row) { public static class DurationConvert { /** ByteBuddy conversion for Duration to NanosDuration base type. */ public static Row toRow(Duration input) { - return Row.withSchema(SCHEMA).addValues(input.getSeconds(), input.getNanos()).build(); + return Row.attachValues(SCHEMA, input.getSeconds(), input.getNanos()); } /** ByteBuddy conversion for NanosDuration base type to Duration. */ diff --git a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaTranslator.java b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaTranslator.java index 7a186471c225..a8db172d1766 100644 --- a/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaTranslator.java +++ b/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoSchemaTranslator.java @@ -189,66 +189,74 @@ static synchronized Schema getSchema(Descriptors.Descriptor descriptor) { return existingSchema; } alreadyVisitedSchemas.put(descriptor, null); - /* OneOfComponentFields refers to the field number in the protobuf where the component subfields - * are. This is needed to prevent double inclusion of the component fields.*/ - Set oneOfComponentFields = Sets.newHashSet(); - /* OneOfFieldLocation stores the field number of the first field in the OneOf. Using this, we can use the location - of the first field in the OneOf as the location of the entire OneOf.*/ - Map oneOfFieldLocation = Maps.newHashMap(); - List fields = Lists.newArrayListWithCapacity(descriptor.getFields().size()); + boolean completed = false; + try { + /* OneOfComponentFields refers to the field number in the protobuf where the component subfields + * are. This is needed to prevent double inclusion of the component fields.*/ + Set oneOfComponentFields = Sets.newHashSet(); + /* OneOfFieldLocation stores the field number of the first field in the OneOf. Using this, we can use the location + of the first field in the OneOf as the location of the entire OneOf.*/ + Map oneOfFieldLocation = Maps.newHashMap(); + List fields = Lists.newArrayListWithCapacity(descriptor.getFields().size()); - // In proto3, an optional field is internally implemented by wrapping it in a synthetic oneof. - // The Descriptor.getRealOneOfs() method is then used to retrieve only the "real" oneofs that - // you explicitly defined, filtering out these automatically generated ones. - // https://github.com/protocolbuffers/protobuf/blob/main/docs/implementing_proto3_presence.md#updating-a- - for (OneofDescriptor oneofDescriptor : descriptor.getRealOneofs()) { - List subFields = Lists.newArrayListWithCapacity(oneofDescriptor.getFieldCount()); - Map enumIds = Maps.newHashMap(); - for (FieldDescriptor fieldDescriptor : oneofDescriptor.getFields()) { - oneOfComponentFields.add(fieldDescriptor.getNumber()); - // Store proto field number in a field option. - FieldType fieldType = beamFieldTypeFromProtoField(fieldDescriptor); - subFields.add( - withFieldNumber( - Field.nullable(fieldDescriptor.getName(), fieldType), fieldDescriptor.getNumber())); - Preconditions.checkArgument( - enumIds.putIfAbsent(fieldDescriptor.getName(), fieldDescriptor.getNumber()) == null); + // In proto3, an optional field is internally implemented by wrapping it in a synthetic oneof. + // The Descriptor.getRealOneOfs() method is then used to retrieve only the "real" oneofs that + // you explicitly defined, filtering out these automatically generated ones. + // https://github.com/protocolbuffers/protobuf/blob/main/docs/implementing_proto3_presence.md#updating-a- + for (OneofDescriptor oneofDescriptor : descriptor.getRealOneofs()) { + List subFields = Lists.newArrayListWithCapacity(oneofDescriptor.getFieldCount()); + Map enumIds = Maps.newHashMap(); + for (FieldDescriptor fieldDescriptor : oneofDescriptor.getFields()) { + oneOfComponentFields.add(fieldDescriptor.getNumber()); + // Store proto field number in a field option. + FieldType fieldType = beamFieldTypeFromProtoField(fieldDescriptor); + subFields.add( + withFieldNumber( + Field.nullable(fieldDescriptor.getName(), fieldType), + fieldDescriptor.getNumber())); + Preconditions.checkArgument( + enumIds.putIfAbsent(fieldDescriptor.getName(), fieldDescriptor.getNumber()) == null); + } + FieldType oneOfType = FieldType.logicalType(OneOfType.create(subFields, enumIds)); + oneOfFieldLocation.put( + oneofDescriptor.getFields().get(0).getNumber(), + Field.nullable(oneofDescriptor.getName(), oneOfType)); } - FieldType oneOfType = FieldType.logicalType(OneOfType.create(subFields, enumIds)); - oneOfFieldLocation.put( - oneofDescriptor.getFields().get(0).getNumber(), - Field.nullable(oneofDescriptor.getName(), oneOfType)); - } - for (Descriptors.FieldDescriptor fieldDescriptor : descriptor.getFields()) { - int fieldDescriptorNumber = fieldDescriptor.getNumber(); - if (!oneOfComponentFields.contains(fieldDescriptorNumber)) { - // Store proto field number in metadata. - FieldType fieldType = beamFieldTypeFromProtoField(fieldDescriptor); - fields.add( - withFieldNumber(Field.of(fieldDescriptor.getName(), fieldType), fieldDescriptorNumber) - .withOptions(getFieldOptions(fieldDescriptor))); - /* Note that descriptor.getFields() returns an iterator in the order of the fields in the .proto file, not - * in field number order. Therefore we can safely insert the OneOfField at the field of its first component.*/ - } else { - Field oneOfField = oneOfFieldLocation.get(fieldDescriptorNumber); - if (oneOfField != null) { - fields.add(oneOfField); + for (Descriptors.FieldDescriptor fieldDescriptor : descriptor.getFields()) { + int fieldDescriptorNumber = fieldDescriptor.getNumber(); + if (!oneOfComponentFields.contains(fieldDescriptorNumber)) { + // Store proto field number in metadata. + FieldType fieldType = beamFieldTypeFromProtoField(fieldDescriptor); + fields.add( + withFieldNumber(Field.of(fieldDescriptor.getName(), fieldType), fieldDescriptorNumber) + .withOptions(getFieldOptions(fieldDescriptor))); + /* Note that descriptor.getFields() returns an iterator in the order of the fields in the .proto file, not + * in field number order. Therefore we can safely insert the OneOfField at the field of its first component.*/ + } else { + Field oneOfField = oneOfFieldLocation.get(fieldDescriptorNumber); + if (oneOfField != null) { + fields.add(oneOfField); + } } } - } - - Schema generatedSchema = - Schema.builder() - .addFields(fields) - .setOptions( - getSchemaOptions(descriptor) - .setOption( - SCHEMA_OPTION_META_TYPE_NAME, FieldType.STRING, descriptor.getFullName())) - .build(); - alreadyVisitedSchemas.put(descriptor, generatedSchema); - return generatedSchema; + Schema generatedSchema = + Schema.builder() + .addFields(fields) + .setOptions( + getSchemaOptions(descriptor) + .setOption( + SCHEMA_OPTION_META_TYPE_NAME, FieldType.STRING, descriptor.getFullName())) + .build(); + alreadyVisitedSchemas.put(descriptor, generatedSchema); + completed = true; + return generatedSchema; + } finally { + if (!completed) { + alreadyVisitedSchemas.remove(descriptor); + } + } } private static FieldType beamFieldTypeFromProtoField( From aba97c365f09e72a3bdb97a3205ae4e8662995f6 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:59:36 -0800 Subject: [PATCH 14/15] Optimize Thrift, AWS2, and Arrow schema providers Caches field accessors and serializable creators in ThriftSchema, optimizes AwsSchemaProvider getter/creator lookups, and uses zero-copy Row.withFieldValueGetters in ArrowConversion. --- .../sdk/extensions/arrow/ArrowConversion.java | 16 +- .../io/aws2/schemas/AwsSchemaProvider.java | 48 ++++- .../beam/sdk/io/thrift/ThriftSchema.java | 173 ++++++++++++------ 3 files changed, 171 insertions(+), 66 deletions(-) diff --git a/sdks/java/extensions/arrow/src/main/java/org/apache/beam/sdk/extensions/arrow/ArrowConversion.java b/sdks/java/extensions/arrow/src/main/java/org/apache/beam/sdk/extensions/arrow/ArrowConversion.java index f1850df2e958..2485c799bc15 100644 --- a/sdks/java/extensions/arrow/src/main/java/org/apache/beam/sdk/extensions/arrow/ArrowConversion.java +++ b/sdks/java/extensions/arrow/src/main/java/org/apache/beam/sdk/extensions/arrow/ArrowConversion.java @@ -40,7 +40,6 @@ import org.apache.arrow.vector.types.TimeUnit; import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.util.Text; -import org.apache.beam.sdk.schemas.CachingFactory; import org.apache.beam.sdk.schemas.Factory; import org.apache.beam.sdk.schemas.FieldValueGetter; import org.apache.beam.sdk.schemas.Schema; @@ -348,10 +347,12 @@ public static org.apache.arrow.vector.types.pojo.Schema arrowSchemaFromInput(Inp public static class RecordBatchRowIterator implements Iterator, AutoCloseable { private static final ArrowValueConverterVisitor valueConverterVisitor = new ArrowValueConverterVisitor(); + private static final TypeDescriptor INTEGER_TYPE_DESCRIPTOR = + TypeDescriptor.of(Integer.class); private final Schema schema; private final VectorSchemaRoot vectorSchemaRoot; - private final Factory>> fieldValueGetters; - private Integer currRowIndex; + private final List> fieldValueGetters; + private int currRowIndex; private static class FieldVectorListValueGetterFactory implements Factory>> { @@ -565,8 +566,8 @@ private RecordBatchRowIterator(Schema schema, VectorSchemaRoot vectorSchemaRoot) this.schema = schema; this.vectorSchemaRoot = vectorSchemaRoot; this.fieldValueGetters = - new CachingFactory<>( - FieldVectorListValueGetterFactory.of(vectorSchemaRoot.getFieldVectors())); + FieldVectorListValueGetterFactory.of(vectorSchemaRoot.getFieldVectors()) + .create(INTEGER_TYPE_DESCRIPTOR, schema); this.currRowIndex = 0; } @@ -586,9 +587,8 @@ public Row next() { throw new IllegalStateException("There are no more Rows."); } Row result = - Row.withSchema(schema) - .withFieldValueGetters( - this.fieldValueGetters, this.currRowIndex, TypeDescriptor.of(Integer.class)); + Row.withFieldValueGetters( + schema, this.fieldValueGetters, this.currRowIndex, INTEGER_TYPE_DESCRIPTOR); this.currRowIndex += 1; return result; } diff --git a/sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/schemas/AwsSchemaProvider.java b/sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/schemas/AwsSchemaProvider.java index 6b3ff6cac861..8ce5d854444d 100644 --- a/sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/schemas/AwsSchemaProvider.java +++ b/sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/schemas/AwsSchemaProvider.java @@ -102,14 +102,51 @@ public SerializableFunction fromRowFunction(TypeDescriptor type) private static class FromRowWithBuilder implements SerializableFunction { + private static final class BoundSetters { + final Schema schema; + final SdkBuilderSetter[] setters; + final int[] fieldIndices; + + BoundSetters(Schema schema, SdkBuilderSetter[] setters, int[] fieldIndices) { + this.schema = schema; + this.setters = setters; + this.fieldIndices = fieldIndices; + } + } + private final Class cls; + private final TypeDescriptor typeDescriptor; private final Factory> factory; + private transient volatile @Nullable BoundSetters cachedBound; FromRowWithBuilder(Class cls, Factory> factory) { this.cls = cls; + this.typeDescriptor = TypeDescriptor.of(cls); this.factory = factory; } + @SuppressWarnings({"ReferenceEquality", "nullness"}) + private BoundSetters getBoundSetters(Schema schema) { + BoundSetters bound = cachedBound; + if (bound != null && (bound.schema == schema || bound.schema.equals(schema))) { + return bound; + } + List all = factory.create(typeDescriptor, schema); + List present = new ArrayList<>(all.size()); + int[] rawIndices = new int[all.size()]; + int count = 0; + for (SdkBuilderSetter s : all) { + if (schema.hasField(s.name())) { + present.add(s); + rawIndices[count++] = schema.indexOf(s.name()); + } + } + int[] indices = java.util.Arrays.copyOf(rawIndices, count); + bound = new BoundSetters(schema, present.toArray(new SdkBuilderSetter[0]), indices); + cachedBound = bound; + return bound; + } + @Override @SuppressWarnings("nullness") // checker doesn't recognize the builder type public T apply(Row row) { @@ -120,12 +157,11 @@ public T apply(Row row) { } } SdkBuilder builder = sdkBuilder(cls); - List setters = factory.create(TypeDescriptor.of(cls), row.getSchema()); - for (SdkBuilderSetter set : setters) { - if (!row.getSchema().hasField(set.name())) { - continue; - } - set.set(builder, row.getValue(set.name())); + BoundSetters bound = getBoundSetters(row.getSchema()); + SdkBuilderSetter[] setters = bound.setters; + int[] fieldIndices = bound.fieldIndices; + for (int i = 0; i < setters.length; i++) { + setters[i].set(builder, row.getValue(fieldIndices[i])); } return builder.build(); } diff --git a/sdks/java/io/thrift/src/main/java/org/apache/beam/sdk/io/thrift/ThriftSchema.java b/sdks/java/io/thrift/src/main/java/org/apache/beam/sdk/io/thrift/ThriftSchema.java index b24f132a0010..49a2e04ec99c 100644 --- a/sdks/java/io/thrift/src/main/java/org/apache/beam/sdk/io/thrift/ThriftSchema.java +++ b/sdks/java/io/thrift/src/main/java/org/apache/beam/sdk/io/thrift/ThriftSchema.java @@ -25,7 +25,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -33,7 +32,6 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; -import java.util.stream.StreamSupport; import org.apache.beam.sdk.schemas.FieldValueGetter; import org.apache.beam.sdk.schemas.FieldValueTypeInformation; import org.apache.beam.sdk.schemas.GetterBasedSchemaProviderV2; @@ -263,16 +261,132 @@ private FieldValueTypeInformation fieldValueTypeInfo(Class type, String field } @Override + @SuppressWarnings({"unchecked", "rawtypes", "nullness"}) public @NonNull SchemaUserTypeCreator schemaTypeCreator( @NonNull TypeDescriptor targetTypeDescriptor, @NonNull Schema schema) { - final Map fieldDescriptors = - schemaFieldDescriptors(targetTypeDescriptor.getRawType(), schema); - return params -> - restoreThriftObject(targetTypeDescriptor.getRawType(), fieldDescriptors, params); + final Class targetClass = targetTypeDescriptor.getRawType(); + ThriftUserTypeCreator creator = new ThriftUserTypeCreator(targetClass, schema); + // Validate constructor and field descriptors eagerly at schema creation time. + creator.resolvePlan(); + return creator; + } + + private static final class ThriftCreatorPlan { + final java.lang.reflect.Constructor constructor; + final TFieldIdEnum[] fields; + final byte[] types; + final TEnum @Nullable [][] enumConstantsByField; + + ThriftCreatorPlan( + java.lang.reflect.Constructor constructor, + TFieldIdEnum[] fields, + byte[] types, + TEnum @Nullable [][] enumConstantsByField) { + this.constructor = constructor; + this.fields = fields; + this.types = types; + this.enumConstantsByField = enumConstantsByField; + } + } + + private static final class ThriftUserTypeCreator implements SchemaUserTypeCreator { + private final Class targetClass; + private final Schema schema; + private transient volatile @Nullable ThriftCreatorPlan cachedPlan; + + ThriftUserTypeCreator(Class targetClass, Schema schema) { + this.targetClass = targetClass; + this.schema = schema; + } + + @SuppressWarnings({"unchecked", "rawtypes", "nullness"}) + ThriftCreatorPlan resolvePlan() { + ThriftCreatorPlan plan = this.cachedPlan; + if (plan != null) { + return plan; + } + final java.lang.reflect.Constructor constructor; + try { + constructor = targetClass.getDeclaredConstructor(); + } catch (NoSuchMethodException e) { + throw new IllegalStateException(e); + } + final Map fieldDescriptors = + schemaFieldDescriptors(targetClass, schema); + int fieldCount = fieldDescriptors.size(); + final TFieldIdEnum[] fields = new TFieldIdEnum[fieldCount]; + final byte[] types = new byte[fieldCount]; + final TEnum @Nullable [][] enumConstantsByField = new TEnum[fieldCount][]; + int idx = 0; + for (Entry entry : fieldDescriptors.entrySet()) { + fields[idx] = entry.getKey(); + FieldMetaData meta = entry.getValue(); + byte type = meta.valueMetaData.type; + types[idx] = type; + if (type == TType.ENUM) { + Class enumClass = ((EnumMetaData) meta.valueMetaData).enumClass; + enumConstantsByField[idx] = enumClass.getEnumConstants(); + } + idx++; + } + plan = new ThriftCreatorPlan(constructor, fields, types, enumConstantsByField); + this.cachedPlan = plan; + return plan; + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes", "nullness"}) + public Object create(Object... params) { + ThriftCreatorPlan plan = resolvePlan(); + TFieldIdEnum[] fields = plan.fields; + byte[] types = plan.types; + TEnum @Nullable [][] enumConstantsByField = plan.enumConstantsByField; + int fieldCount = fields.length; + if (params.length != fieldCount) { + throw new IllegalArgumentException( + String.format( + "The parameter list: %s does not match the expected fields: %s", + Arrays.toString(params), Arrays.toString(fields))); + } + try { + final TBase thrift = (TBase) plan.constructor.newInstance(); + for (int i = 0; i < fieldCount; i++) { + Object value = params[i]; + if (value == null) { + continue; + } + final Object actualValue; + switch (types[i]) { + case TType.SET: + if (value instanceof java.util.Collection) { + actualValue = new java.util.HashSet<>((java.util.Collection) value); + } else { + java.util.Set set = new java.util.HashSet<>(); + for (Object elem : (Iterable) value) { + set.add(elem); + } + actualValue = set; + } + break; + case TType.ENUM: + TEnum[] constants = enumConstantsByField[i]; + actualValue = constants[(Integer) value]; + break; + default: + actualValue = value; + break; + } + thrift.setFieldValue(fields[i], actualValue); + } + return thrift; + } catch (Exception e) { + throw new IllegalStateException(e); + } + } } @SuppressWarnings("nullness") - private Map schemaFieldDescriptors( + private static Map schemaFieldDescriptors( Class targetClass, Schema schema) { final Map fieldDescriptors = thriftFieldDescriptors(targetClass); final Map fields = @@ -290,51 +404,6 @@ private Map schemaFieldDescriptors( LinkedHashMap::new)); } - private > T restoreThriftObject( - Class targetClass, Map fields, Object[] params) { - if (params.length != fields.size()) { - throw new IllegalArgumentException( - String.format( - "The parameter list: %s does not match the expected fields: %s", - Arrays.toString(params), fields.keySet())); - } - try { - @SuppressWarnings("unchecked") - final T thrift = (T) targetClass.getDeclaredConstructor().newInstance(); - final Iterator> iter = fields.entrySet().iterator(); - Stream.of(params).forEach(param -> setThriftField(thrift, iter.next(), param)); - return thrift; - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - private > void setThriftField( - T thrift, Entry fieldDescriptor, Object value) { - final FieldT field = fieldDescriptor.getKey(); - final FieldMetaData descriptor = fieldDescriptor.getValue(); - if (value != null) { - final Object actualValue; - switch (descriptor.valueMetaData.type) { - case TType.SET: - actualValue = - StreamSupport.stream(((Iterable) value).spliterator(), false) - .collect(Collectors.toSet()); - break; - case TType.ENUM: - final Class enumClass = - ((EnumMetaData) descriptor.valueMetaData).enumClass; - @SuppressWarnings("nullness") // it's either "nullness" or "unsafe", apparently - final TEnum @NonNull [] enumConstants = enumClass.getEnumConstants(); - actualValue = enumConstants[(Integer) value]; - break; - default: - actualValue = value; - } - thrift.setFieldValue(field, actualValue); - } - } - private & TEnum> FieldType beamType(FieldValueMetaData metadata) { if (metadata.isTypedef()) { final FieldType beamType = typedefs.get(metadata.getTypedefName()); From 441fc9fafc5e1512bbfc2d2f97ac67be573b19a7 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Thu, 26 Nov 2026 21:59:52 -0800 Subject: [PATCH 15/15] Add representative JMH benchmarks for schema performance Adds 58 JMH microbenchmarks (plus JUnit smoke test) covering Schema/Row operations, built-in LogicalTypes, RowCoder/SchemaCoder encode/decode/byte-size (flat, nullable, nested, wide, POJO, JavaBean, lazy iterables), and core schema transforms (Select, Cast, SchemaAggregateFn). --- .../jmh/schemas/RowAndSchemaBenchmark.java | 447 ++++++++++ .../sdk/jmh/schemas/SchemaCoderBenchmark.java | 831 ++++++++++++++++++ .../schemas/SchemaTransformsBenchmark.java | 290 ++++++ .../SchemaOptimizationBenchmarksTest.java | 127 +++ 4 files changed, 1695 insertions(+) create mode 100644 sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/RowAndSchemaBenchmark.java create mode 100644 sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaCoderBenchmark.java create mode 100644 sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaTransformsBenchmark.java create mode 100644 sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/schemas/SchemaOptimizationBenchmarksTest.java diff --git a/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/RowAndSchemaBenchmark.java b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/RowAndSchemaBenchmark.java new file mode 100644 index 000000000000..a13630618bf8 --- /dev/null +++ b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/RowAndSchemaBenchmark.java @@ -0,0 +1,447 @@ +/* + * 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.beam.sdk.jmh.schemas; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import org.apache.beam.sdk.coders.RowCoder; +import org.apache.beam.sdk.jmh.schemas.SchemaCoderBenchmark.Color; +import org.apache.beam.sdk.jmh.schemas.SchemaCoderBenchmark.FlatJavaBean; +import org.apache.beam.sdk.jmh.schemas.SchemaCoderBenchmark.FlatPojo; +import org.apache.beam.sdk.jmh.schemas.SchemaCoderBenchmark.NestedPojo; +import org.apache.beam.sdk.jmh.schemas.SchemaCoderBenchmark.RichPojo; +import org.apache.beam.sdk.schemas.JavaFieldSchema; +import org.apache.beam.sdk.schemas.RowMessages; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.SchemaCoder; +import org.apache.beam.sdk.schemas.SchemaRegistry; +import org.apache.beam.sdk.schemas.logicaltypes.DateTime; +import org.apache.beam.sdk.schemas.logicaltypes.EnumerationType; +import org.apache.beam.sdk.schemas.logicaltypes.FixedPrecisionNumeric; +import org.apache.beam.sdk.schemas.logicaltypes.OneOfType; +import org.apache.beam.sdk.schemas.logicaltypes.Timestamp; +import org.apache.beam.sdk.schemas.logicaltypes.UuidLogicalType; +import org.apache.beam.sdk.schemas.utils.JsonUtils; +import org.apache.beam.sdk.transforms.SerializableFunction; +import org.apache.beam.sdk.transforms.SimpleFunction; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.TypeDescriptor; +import org.joda.time.Instant; +import org.joda.time.ReadableDateTime; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +/** + * JMH benchmarks for {@link Row} ({@code RowWithStorage} and {@code RowWithGetters}), {@link + * Schema}, {@link Schema.LogicalType}, {@link RowMessages}, {@link JsonUtils}, and {@code + * GetterBasedSchemaProvider} / ByteBuddy conversions. + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@Fork(1) +@SuppressWarnings({"nullness", "rawtypes"}) +public class RowAndSchemaBenchmark { + + @State(Scope.Thread) + public static class RowState { + Schema schemaA; + Schema schemaB; // Equal fields, different random UUID + Row rowStorageA; + Row rowStorageB; + Row rowWithGettersRich; + int fieldIdxTags; + int fieldIdxCounts; + int fieldIdxAddress; + + SerializableFunction flatPojoToRow; + SerializableFunction flatPojoFromRow; + FlatPojo flatPojo; + Row flatPojoRowStorage; + + SerializableFunction richPojoToRow; + SerializableFunction richPojoFromRow; + RichPojo richPojo; + Row richPojoRowStorage; + + SerializableFunction beanToRow; + SerializableFunction beanFromRow; + FlatJavaBean bean; + Row beanRowStorage; + + SimpleFunction rowToBytes; + Schema jsonSchema; + Row jsonRow; + SerializableFunction rowToJsonBytes; + SerializableFunction jsonBytesToRow; + byte[] jsonBytes; + + Timestamp tsMicros; + java.time.Instant javaInstant; + Row tsBaseRow; + + DateTime dtLogical; + LocalDateTime ldt; + Row dtBaseRow; + + UuidLogicalType uuidLogical; + UUID uuid; + Row uuidBaseRow; + + EnumerationType enumLogical; + OneOfType oneOfLogical; + OneOfType.Value oneOfVal; + Row oneOfBaseRow; + + FixedPrecisionNumeric fixedNumeric; + BigDecimal numericVal; + + // Non-constant benchmark inputs to prevent JIT constant folding. + String enumLookupName; + int schemaFieldIdx; + Schema.TypeName[] typeNames; + int typeNameCursor; + + @Setup + public void setUp() throws Exception { + schemaA = buildTestSchema(); + schemaB = buildTestSchema(); + + Instant tsA = Instant.ofEpochMilli(1_700_000_000_000L); + Instant tsB = Instant.ofEpochMilli(1_700_000_000_000L); + rowStorageA = + Row.withSchema(schemaA) + .addValues( + 100_000L, + String.valueOf("user-42".toCharArray()), + 100_000, + 99.95, + true, + tsA, + new byte[] {1, 2, 3, 4}) + .build(); + rowStorageB = + Row.withSchema(schemaB) + .addValues( + Long.valueOf(100_000L), + String.valueOf("user-42".toCharArray()), + Integer.valueOf(100_000), + Double.valueOf(99.95), + true, + tsB, + new byte[] {1, 2, 3, 4}) + .build(); + Instant ts = tsA; + + SchemaRegistry registry = SchemaRegistry.createDefault(); + SchemaCoder flatCoder = registry.getSchemaCoder(FlatPojo.class); + flatPojoToRow = flatCoder.getToRowFunction(); + flatPojoFromRow = flatCoder.getFromRowFunction(); + flatPojo = new FlatPojo(); + flatPojo.fByte = 7; + flatPojo.fShort = 42; + flatPojo.fInt = 123; + flatPojo.fLong = 456L; + flatPojo.fFloat = 1.5f; + flatPojo.fDouble = 2.5; + flatPojo.fBool = true; + flatPojo.fString1 = "alpha"; + flatPojo.fString2 = "beta"; + flatPojo.fInstant = ts; + flatPojoRowStorage = copyToStorage(flatCoder.getSchema(), flatPojoToRow.apply(flatPojo)); + + SchemaCoder richCoder = registry.getSchemaCoder(RichPojo.class); + richPojoToRow = richCoder.getToRowFunction(); + richPojoFromRow = richCoder.getFromRowFunction(); + Map counts = new HashMap<>(); + counts.put("k1", 1L); + counts.put("k2", 2L); + counts.put("k3", 3L); + counts.put("k4", 4L); + richPojo = new RichPojo(); + richPojo.id = 42L; + richPojo.name = "widget"; + richPojo.score = 98.5; + richPojo.active = true; + richPojo.ts = ts; + richPojo.color = Color.BLUE; + richPojo.uuid = new UUID(0x123456789ABCDEF0L, 0x0FEDCBA987654321L); + richPojo.createdAt = LocalDateTime.of(2026, 5, 15, 14, 30, 0); + richPojo.tags = Arrays.asList("a", "b", "c", "d"); + richPojo.counts = counts; + richPojo.address = new NestedPojo("Seattle", 98101, 47.6062); + rowWithGettersRich = richPojoToRow.apply(richPojo); + Schema richSchema = richCoder.getSchema(); + fieldIdxTags = richSchema.indexOf("tags"); + fieldIdxCounts = richSchema.indexOf("counts"); + fieldIdxAddress = richSchema.indexOf("address"); + richPojoRowStorage = copyToStorage(richSchema, rowWithGettersRich); + + SchemaCoder beanCoder = registry.getSchemaCoder(FlatJavaBean.class); + beanToRow = beanCoder.getToRowFunction(); + beanFromRow = beanCoder.getFromRowFunction(); + bean = new FlatJavaBean(); + bean.setFInt(123); + bean.setFLong(456L); + bean.setFDouble(2.5); + bean.setFBool(true); + bean.setFString1("alpha"); + bean.setFString2("beta"); + bean.setFInstant(ts); + bean.setTags(Arrays.asList("a", "b", "c", "d")); + bean.setCounts(counts); + beanRowStorage = copyToStorage(beanCoder.getSchema(), beanToRow.apply(bean)); + + JavaFieldSchema provider = new JavaFieldSchema(); + rowToBytes = RowMessages.rowToBytesFn(provider, TypeDescriptor.of(FlatPojo.class), flatCoder); + + jsonSchema = + Schema.builder() + .addInt64Field("id") + .addStringField("user") + .addInt32Field("count") + .addDoubleField("amount") + .addBooleanField("active") + .addDateTimeField("ts") + .build(); + jsonRow = Row.withSchema(jsonSchema).addValues(1L, "user-42", 100, 99.95, true, ts).build(); + rowToJsonBytes = JsonUtils.getRowToJsonBytesFunction(jsonSchema); + jsonBytesToRow = JsonUtils.getJsonBytesToRowFunction(jsonSchema); + jsonBytes = rowToJsonBytes.apply(jsonRow); + + tsMicros = Timestamp.MICROS; + javaInstant = java.time.Instant.ofEpochSecond(1_700_000_000L, 123_456_000L); + tsBaseRow = tsMicros.toBaseType(javaInstant); + + dtLogical = new DateTime(); + ldt = LocalDateTime.of(2026, 5, 15, 14, 30, 45); + dtBaseRow = dtLogical.toBaseType(ldt); + + uuidLogical = new UuidLogicalType(); + uuid = new UUID(0x123456789ABCDEF0L, 0x0FEDCBA987654321L); + uuidBaseRow = uuidLogical.toBaseType(uuid); + + enumLogical = EnumerationType.create("RED", "GREEN", "BLUE", "YELLOW"); + oneOfLogical = + OneOfType.create( + Schema.Field.of("a", FieldType.STRING), + Schema.Field.of("b", FieldType.INT64), + Schema.Field.of("c", FieldType.DOUBLE), + Schema.Field.of("d", FieldType.BOOLEAN)); + oneOfVal = oneOfLogical.createValue("b", 999L); + oneOfBaseRow = oneOfLogical.toBaseType(oneOfVal); + + fixedNumeric = FixedPrecisionNumeric.of(10, 2); + numericVal = new BigDecimal("1234.56"); + + enumLookupName = String.valueOf("BLUE".toCharArray()); + schemaFieldIdx = 3; + typeNames = Schema.TypeName.values(); + typeNameCursor = 0; + } + + private static Schema buildTestSchema() { + return Schema.builder() + .addInt64Field("id") + .addStringField("user") + .addInt32Field("count") + .addDoubleField("amount") + .addBooleanField("active") + .addDateTimeField("ts") + .addByteArrayField("payload") + .build(); + } + + private static Row copyToStorage(Schema schema, Row row) throws Exception { + RowCoder coder = RowCoder.of(schema); + java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); + coder.encode(row, baos); + return coder.decode(new java.io.ByteArrayInputStream(baos.toByteArray())); + } + } + + @Benchmark + public boolean rowEqualsDifferentSchemaUuid(RowState s) { + return s.rowStorageA.equals(s.rowStorageB); + } + + @Benchmark + public int rowHashCode(RowState s) { + return s.rowStorageA.hashCode(); + } + + @Benchmark + public ReadableDateTime rowGetDateTime(RowState s) { + return s.rowStorageA.getDateTime(5); + } + + @Benchmark + public List rowGetBaseValues(RowState s) { + return s.rowStorageA.getBaseValues(); + } + + @Benchmark + public void rowWithGettersCachedCollectionRead(RowState s, Blackhole bh) { + // Hits RowWithGetters cache for ARRAY and MAP fields + bh.consume(s.rowWithGettersRich.getValue(s.fieldIdxTags)); + bh.consume(s.rowWithGettersRich.getValue(s.fieldIdxCounts)); + } + + @Benchmark + public void rowWithGettersFreshReadAll(RowState s, Blackhole bh) { + Row r = s.richPojoToRow.apply(s.richPojo); + int n = r.getFieldCount(); + for (int i = 0; i < n; i++) { + bh.consume(r.getValue(i)); + } + } + + @Benchmark + public Object rowWithGettersNestedRowRead(RowState s) { + Row sub = s.rowWithGettersRich.getRow(s.fieldIdxAddress); + return sub.getValue(0); + } + + @Benchmark + public FlatPojo flatPojoFromRow(RowState s) { + return s.flatPojoFromRow.apply(s.flatPojoRowStorage); + } + + @Benchmark + public RichPojo richPojoFromRow(RowState s) { + return s.richPojoFromRow.apply(s.richPojoRowStorage); + } + + @Benchmark + public FlatJavaBean javaBeanFromRow(RowState s) { + return s.beanFromRow.apply(s.beanRowStorage); + } + + @Benchmark + public boolean schemaEqualsDifferentUuid(RowState s) { + return s.schemaA.equals(s.schemaB); + } + + @Benchmark + public boolean schemaEquivalent(RowState s) { + return s.schemaA.equivalent(s.schemaB); + } + + @Benchmark + public String schemaNameOf(RowState s) { + return s.schemaA.nameOf(s.schemaFieldIdx); + } + + @Benchmark + public List schemaGetFieldNames(RowState s) { + return s.schemaA.getFieldNames(); + } + + @Benchmark + public boolean typeNamePredicates(RowState s) { + int idx = s.typeNameCursor + 1; + if (idx >= s.typeNames.length) { + idx = 0; + } + s.typeNameCursor = idx; + Schema.TypeName t = s.typeNames[idx]; + return t.isPrimitiveType() && t.isNumericType() && !t.isCollectionType(); + } + + @Benchmark + public byte[] rowMessagesToBytes(RowState s) { + return s.rowToBytes.apply(s.flatPojoRowStorage); + } + + @Benchmark + public byte[] jsonRowToBytes(RowState s) { + return s.rowToJsonBytes.apply(s.jsonRow); + } + + @Benchmark + public Row jsonBytesToRow(RowState s) { + return s.jsonBytesToRow.apply(s.jsonBytes); + } + + @Benchmark + public Row logicalTimestampToBase(RowState s) { + return s.tsMicros.toBaseType(s.javaInstant); + } + + @Benchmark + public java.time.Instant logicalTimestampToInput(RowState s) { + return s.tsMicros.toInputType(s.tsBaseRow); + } + + @Benchmark + public Row logicalDateTimeToBase(RowState s) { + return s.dtLogical.toBaseType(s.ldt); + } + + @Benchmark + public LocalDateTime logicalDateTimeToInput(RowState s) { + return s.dtLogical.toInputType(s.dtBaseRow); + } + + @Benchmark + public Row logicalUuidToBase(RowState s) { + return s.uuidLogical.toBaseType(s.uuid); + } + + @Benchmark + public UUID logicalUuidToInput(RowState s) { + return s.uuidLogical.toInputType(s.uuidBaseRow); + } + + @Benchmark + public EnumerationType.Value logicalEnumValueOf(RowState s) { + return s.enumLogical.valueOf(s.enumLookupName); + } + + @Benchmark + public Row logicalOneOfToBase(RowState s) { + return s.oneOfLogical.toBaseType(s.oneOfVal); + } + + @Benchmark + public OneOfType.Value logicalOneOfToInput(RowState s) { + return s.oneOfLogical.toInputType(s.oneOfBaseRow); + } + + @Benchmark + public BigDecimal logicalFixedNumericToInput(RowState s) { + return s.fixedNumeric.toInputType(s.numericVal); + } +} diff --git a/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaCoderBenchmark.java b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaCoderBenchmark.java new file mode 100644 index 000000000000..78d94c1f9ef0 --- /dev/null +++ b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaCoderBenchmark.java @@ -0,0 +1,831 @@ +/* + * 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.beam.sdk.jmh.schemas; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Observer; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.RowCoder; +import org.apache.beam.sdk.schemas.JavaBeanSchema; +import org.apache.beam.sdk.schemas.JavaFieldSchema; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.SchemaCoder; +import org.apache.beam.sdk.schemas.SchemaRegistry; +import org.apache.beam.sdk.schemas.annotations.DefaultSchema; +import org.apache.beam.sdk.schemas.logicaltypes.Date; +import org.apache.beam.sdk.schemas.logicaltypes.DateTime; +import org.apache.beam.sdk.schemas.logicaltypes.EnumerationType; +import org.apache.beam.sdk.schemas.logicaltypes.MicrosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.NanosDuration; +import org.apache.beam.sdk.schemas.logicaltypes.NanosInstant; +import org.apache.beam.sdk.schemas.logicaltypes.OneOfType; +import org.apache.beam.sdk.schemas.logicaltypes.Time; +import org.apache.beam.sdk.schemas.logicaltypes.Timestamp; +import org.apache.beam.sdk.schemas.logicaltypes.UuidLogicalType; +import org.apache.beam.sdk.util.common.ElementByteSizeObservableIterable; +import org.apache.beam.sdk.util.common.ElementByteSizeObservableIterator; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; +import org.apache.beam.sdk.values.Row; +import org.joda.time.Instant; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +/** + * JMH benchmarks for {@link RowCoder} and {@link SchemaCoder} encoding, decoding, and byte-size + * observation across flat, nullable, static-encoding, nested, logical-type, POJO, and JavaBean + * schemas. + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@Fork(1) +@SuppressWarnings({"nullness", "rawtypes"}) +public class SchemaCoderBenchmark { + + /** Reusable unsynchronized OutputStream reset per call to isolate coder CPU/allocations. */ + private static final class ResettableByteArrayOutputStream extends OutputStream { + private byte[] buf; + private int count; + + ResettableByteArrayOutputStream(int size) { + this.buf = new byte[size]; + } + + @Override + public void write(int b) { + if (count >= buf.length) { + buf = Arrays.copyOf(buf, buf.length << 1); + } + buf[count++] = (byte) b; + } + + @Override + public void write(byte[] b, int off, int len) { + if (count + len > buf.length) { + buf = Arrays.copyOf(buf, Math.max(buf.length << 1, count + len)); + } + System.arraycopy(b, off, buf, count, len); + count += len; + } + + void reset() { + count = 0; + } + + int writtenSize() { + return count; + } + } + + /** Reusable unsynchronized InputStream reset to position 0 to isolate decode costs. */ + private static final class ResettableByteArrayInputStream extends InputStream { + private final byte[] buf; + private int pos; + + ResettableByteArrayInputStream(byte[] buf) { + this.buf = buf; + } + + @Override + public int read() { + return pos < buf.length ? (buf[pos++] & 0xff) : -1; + } + + @Override + public int read(byte[] b, int off, int len) { + if (pos >= buf.length) { + return -1; + } + int avail = buf.length - pos; + int n = Math.min(len, avail); + System.arraycopy(buf, pos, b, off, n); + pos += n; + return n; + } + + @Override + public int available() { + return buf.length - pos; + } + + void rewind() { + pos = 0; + } + } + + /** Counting {@link ElementByteSizeObserver} simulating Dataflow/runner size observer. */ + private static final class CountingByteSizeObserver extends ElementByteSizeObserver { + long lastSize; + + @Override + protected void reportElementSize(long elementSize) { + lastSize += elementSize; + } + + long resetAndAdvance() { + advance(); + long r = lastSize; + lastSize = 0; + return r; + } + } + + /** Lazy observable iterable mimicking Dataflow GroupingShuffleReader / streaming state. */ + private static final class FakeLazyIterable + extends ElementByteSizeObservableIterable> { + private final List backing; + + FakeLazyIterable(List backing) { + this.backing = backing; + } + + @Override + public void addObserver(Observer observer) { + // Do not retain observers across millions of repeated benchmark calls; simply mirror the + // superclass side effect of marking lazy byte-size observation without OOM accumulation. + } + + @Override + protected ElementByteSizeObservableIterator createIterator() { + final Iterator delegate = backing.iterator(); + return new ElementByteSizeObservableIterator() { + @Override + public boolean hasNext() { + return delegate.hasNext(); + } + + @Override + public Row next() { + Row r = delegate.next(); + notifyValueReturned(64L); + return r; + } + }; + } + } + + /** Enum for schema POJO/JavaBean benchmarks. */ + public enum Color { + RED, + GREEN, + BLUE, + YELLOW + } + + /** Nested POJO for SchemaCoder benchmarks. */ + @DefaultSchema(JavaFieldSchema.class) + public static class NestedPojo { + public String city; + public int zip; + public double lat; + + public NestedPojo() {} + + public NestedPojo(String city, int zip, double lat) { + this.city = city; + this.zip = zip; + this.lat = lat; + } + + @Override + public String toString() { + return city + ":" + zip + ":" + lat; + } + } + + /** Representative flat primitive POJO matching typical Beam user records. */ + @DefaultSchema(JavaFieldSchema.class) + public static class FlatPojo { + public byte fByte; + public short fShort; + public int fInt; + public long fLong; + public float fFloat; + public double fDouble; + public boolean fBool; + public String fString1; + public String fString2; + public Instant fInstant; + + public FlatPojo() {} + } + + /** Rich POJO with containers, enum, nested POJO, UUID, and JSR-310 fields. */ + @DefaultSchema(JavaFieldSchema.class) + public static class RichPojo { + public long id; + public String name; + public double score; + public boolean active; + public Instant ts; + public Color color; + public UUID uuid; + public LocalDateTime createdAt; + public List tags; + public Map counts; + public NestedPojo address; + + public RichPojo() {} + } + + /** Classic mutable JavaBean (exercises SetterBasedCreatorFactory in JavaBeanSchema). */ + @DefaultSchema(JavaBeanSchema.class) + public static class FlatJavaBean { + private int fInt; + private long fLong; + private double fDouble; + private boolean fBool; + private String fString1; + private String fString2; + private Instant fInstant; + private List tags; + private Map counts; + + public int getFInt() { + return fInt; + } + + public void setFInt(int v) { + this.fInt = v; + } + + public long getFLong() { + return fLong; + } + + public void setFLong(long v) { + this.fLong = v; + } + + public double getFDouble() { + return fDouble; + } + + public void setFDouble(double v) { + this.fDouble = v; + } + + public boolean isFBool() { + return fBool; + } + + public void setFBool(boolean v) { + this.fBool = v; + } + + public String getFString1() { + return fString1; + } + + public void setFString1(String v) { + this.fString1 = v; + } + + public String getFString2() { + return fString2; + } + + public void setFString2(String v) { + this.fString2 = v; + } + + public Instant getFInstant() { + return fInstant; + } + + public void setFInstant(Instant v) { + this.fInstant = v; + } + + public List getTags() { + return tags; + } + + public void setTags(List v) { + this.tags = v; + } + + public Map getCounts() { + return counts; + } + + public void setCounts(Map v) { + this.counts = v; + } + } + + @State(Scope.Thread) + public static class CoderState { + Schema flatSchema; + RowCoder flatCoder; + Row flatRow; + ResettableByteArrayInputStream flatIn; + + Schema staticSchema; + RowCoder staticCoder; + Row staticRow; + ResettableByteArrayInputStream staticIn; + + Schema nullableSchema; + RowCoder nullableCoder; + Row nullableNoNullsRow; + Row nullableSparseNullsRow; + ResettableByteArrayInputStream nullableNoNullsIn; + ResettableByteArrayInputStream nullableSparseNullsIn; + + Schema wideSchema; + RowCoder wideCoder; + Row wideRow; + ResettableByteArrayInputStream wideIn; + + Schema nestedSchema; + RowCoder nestedCoder; + Row nestedRow; + ResettableByteArrayInputStream nestedIn; + + Schema logicalSchema; + RowCoder logicalCoder; + Row logicalRow; + ResettableByteArrayInputStream logicalIn; + + Schema groupedOutputSchema; + RowCoder groupedOutputCoder; + Row groupedOutputRow; + + SchemaCoder flatPojoCoder; + FlatPojo flatPojo; + ResettableByteArrayInputStream flatPojoIn; + + SchemaCoder richPojoCoder; + RichPojo richPojo; + ResettableByteArrayInputStream richPojoIn; + + SchemaCoder javaBeanCoder; + FlatJavaBean javaBean; + ResettableByteArrayInputStream javaBeanIn; + + ResettableByteArrayOutputStream out; + CountingByteSizeObserver observer; + + @Setup + public void setUp() throws Exception { + out = new ResettableByteArrayOutputStream(4096); + observer = new CountingByteSizeObserver(); + + flatSchema = + Schema.builder() + .addByteField("f_byte") + .addInt16Field("f_short") + .addInt32Field("f_int") + .addInt64Field("f_long") + .addFloatField("f_float") + .addDoubleField("f_double") + .addBooleanField("f_bool") + .addStringField("f_str1") + .addStringField("f_str2") + .addDateTimeField("f_dt") + .addByteArrayField("f_bytes") + .addDecimalField("f_dec") + .build(); + flatCoder = RowCoder.of(flatSchema); + flatRow = + Row.withSchema(flatSchema) + .addValues( + (byte) 7, + (short) 42, + 123456, + 9_876_543_210L, + 3.14f, + 2.718281828, + true, + "us-central1", + "purchase-event-payload", + Instant.ofEpochMilli(1_700_000_000_000L), + "raw-bytes-123456".getBytes(StandardCharsets.UTF_8), + new BigDecimal("12345.67")) + .build(); + flatIn = encodeToStream(flatCoder, flatRow); + + staticSchema = + Schema.builder() + .addInt32Field("f_int") + .addInt64Field("f_long") + .addDoubleField("f_double") + .addBooleanField("f_bool") + .addStringField("f_str") + .addDateTimeField("f_dt") + .setOptions( + Schema.Options.builder() + .setOption("beam:option:row:static_encoding", FieldType.BOOLEAN, true) + .build()) + .build(); + staticCoder = RowCoder.of(staticSchema); + staticRow = + Row.withSchema(staticSchema) + .addValues( + 42, + 123_456_789L, + 99.95, + false, + "order-item-123", + Instant.ofEpochMilli(1_700_000_000_000L)) + .build(); + staticIn = encodeToStream(staticCoder, staticRow); + + nullableSchema = + Schema.builder() + .addInt64Field("id") + .addStringField("key") + .addNullableInt32Field("n_int") + .addNullableInt64Field("n_long") + .addNullableDoubleField("n_double") + .addNullableStringField("n_str1") + .addNullableStringField("n_str2") + .addNullableBooleanField("n_bool") + .addNullableDateTimeField("n_dt") + .addNullableByteArrayField("n_bytes") + .build(); + nullableCoder = RowCoder.of(nullableSchema); + nullableNoNullsRow = + Row.withSchema(nullableSchema) + .addValues( + 1L, + "k1", + 10, + 200L, + 1.5, + "alpha", + "beta", + true, + Instant.ofEpochMilli(1_700_000_000_000L), + new byte[] {1, 2, 3, 4}) + .build(); + nullableSparseNullsRow = + Row.withSchema(nullableSchema) + .addValues( + 1L, + "k1", + 10, + null, + 1.5, + null, + "beta", + null, + Instant.ofEpochMilli(1_700_000_000_000L), + null) + .build(); + nullableNoNullsIn = encodeToStream(nullableCoder, nullableNoNullsRow); + nullableSparseNullsIn = encodeToStream(nullableCoder, nullableSparseNullsRow); + + Schema.Builder wideBuilder = Schema.builder(); + Object[] wideVals = new Object[40]; + for (int i = 0; i < 40; i++) { + switch (i % 4) { + case 0: + wideBuilder.addInt64Field("l_" + i); + wideVals[i] = 1000L + i; + break; + case 1: + wideBuilder.addDoubleField("d_" + i); + wideVals[i] = i * 1.25; + break; + case 2: + wideBuilder.addInt32Field("i_" + i); + wideVals[i] = i * 7; + break; + default: + wideBuilder.addNullableStringField("s_" + i); + wideVals[i] = (i % 8 == 3) ? null : "val_" + i; + break; + } + } + wideSchema = wideBuilder.build(); + wideCoder = RowCoder.of(wideSchema); + wideRow = Row.withSchema(wideSchema).addValues(wideVals).build(); + wideIn = encodeToStream(wideCoder, wideRow); + + Schema childSchema = + Schema.builder() + .addStringField("name") + .addInt32Field("qty") + .addDoubleField("price") + .build(); + nestedSchema = + Schema.builder() + .addInt64Field("orderId") + .addRowField("primary", childSchema) + .addArrayField("tags", FieldType.STRING) + .addArrayField("items", FieldType.row(childSchema)) + .addMapField("attrs", FieldType.STRING, FieldType.INT64) + .build(); + nestedCoder = RowCoder.of(nestedSchema); + List items = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + items.add(Row.withSchema(childSchema).addValues("item-" + i, i + 1, 9.99 * i).build()); + } + Map attrs = new HashMap<>(); + attrs.put("k1", 10L); + attrs.put("k2", 20L); + attrs.put("k3", 30L); + attrs.put("k4", 40L); + nestedRow = + Row.withSchema(nestedSchema) + .addValues( + 42L, + Row.withSchema(childSchema).addValues("main", 3, 19.99).build(), + Arrays.asList("fast", "sale", "prime", "us"), + items, + attrs) + .build(); + nestedIn = encodeToStream(nestedCoder, nestedRow); + + EnumerationType enumType = EnumerationType.create("RED", "GREEN", "BLUE", "YELLOW"); + OneOfType oneOfType = + OneOfType.create( + Schema.Field.of("str_val", FieldType.STRING), + Schema.Field.of("int_val", FieldType.INT64), + Schema.Field.of("dbl_val", FieldType.DOUBLE)); + logicalSchema = + Schema.builder() + .addLogicalTypeField("l_date", new Date()) + .addLogicalTypeField("l_time", new Time()) + .addLogicalTypeField("l_dt", new DateTime()) + .addLogicalTypeField("l_ts_micros", Timestamp.MICROS) + .addLogicalTypeField("l_micros", new MicrosInstant()) + .addLogicalTypeField("l_nanos_inst", new NanosInstant()) + .addLogicalTypeField("l_nanos_dur", new NanosDuration()) + .addLogicalTypeField("l_uuid", new UuidLogicalType()) + .addLogicalTypeField("l_enum", enumType) + .addLogicalTypeField("l_oneof", oneOfType) + .build(); + logicalCoder = RowCoder.of(logicalSchema); + logicalRow = + Row.withSchema(logicalSchema) + .addValues( + LocalDate.of(2026, 5, 15), + LocalTime.of(14, 30, 45, 123_000_000), + LocalDateTime.of(2026, 5, 15, 14, 30, 45), + java.time.Instant.ofEpochSecond(1_700_000_000L, 123_456_000L), + java.time.Instant.ofEpochSecond(1_700_000_000L, 654_321_000L), + java.time.Instant.ofEpochSecond(1_700_000_000L, 987_654_321L), + java.time.Duration.ofSeconds(120, 500_000_000L), + new UUID(0x123456789ABCDEF0L, 0x0FEDCBA987654321L), + enumType.valueOf("BLUE"), + oneOfType.createValue("int_val", 999L)) + .build(); + logicalIn = encodeToStream(logicalCoder, logicalRow); + + Schema keySchema = Schema.builder().addStringField("userId").build(); + groupedOutputSchema = + Schema.builder() + .addRowField("key", keySchema) + .addIterableField("value", FieldType.row(flatSchema)) + .build(); + groupedOutputCoder = RowCoder.of(groupedOutputSchema); + List groupedVals = new ArrayList<>(200); + for (int i = 0; i < 200; i++) { + groupedVals.add(flatRow); + } + groupedOutputRow = + Row.withSchema(groupedOutputSchema) + .attachValues( + Row.withSchema(keySchema).addValues("user-1").build(), + new FakeLazyIterable(groupedVals)); + + SchemaRegistry registry = SchemaRegistry.createDefault(); + flatPojoCoder = registry.getSchemaCoder(FlatPojo.class); + flatPojo = new FlatPojo(); + flatPojo.fByte = 7; + flatPojo.fShort = 42; + flatPojo.fInt = 123456; + flatPojo.fLong = 9_876_543_210L; + flatPojo.fFloat = 12.345f; + flatPojo.fDouble = 67.8901234; + flatPojo.fBool = true; + flatPojo.fString1 = "us-central1"; + flatPojo.fString2 = "purchase-event-payload"; + flatPojo.fInstant = Instant.ofEpochMilli(1_700_000_000_000L); + flatPojoIn = encodeToStream(flatPojoCoder, flatPojo); + + richPojoCoder = registry.getSchemaCoder(RichPojo.class); + richPojo = new RichPojo(); + richPojo.id = 42L; + richPojo.name = "widget"; + richPojo.score = 98.5; + richPojo.active = true; + richPojo.ts = Instant.ofEpochMilli(1_700_000_000_000L); + richPojo.color = Color.BLUE; + richPojo.uuid = new UUID(0x123456789ABCDEF0L, 0x0FEDCBA987654321L); + richPojo.createdAt = LocalDateTime.of(2026, 5, 15, 14, 30, 0); + richPojo.tags = Arrays.asList("a", "b", "c", "d"); + richPojo.counts = new HashMap<>(attrs); + richPojo.address = new NestedPojo("Seattle", 98101, 47.6062); + richPojoIn = encodeToStream(richPojoCoder, richPojo); + + javaBeanCoder = registry.getSchemaCoder(FlatJavaBean.class); + javaBean = new FlatJavaBean(); + javaBean.setFInt(123456); + javaBean.setFLong(9_876_543_210L); + javaBean.setFDouble(67.8901234); + javaBean.setFBool(true); + javaBean.setFString1("us-central1"); + javaBean.setFString2("purchase-event-payload"); + javaBean.setFInstant(Instant.ofEpochMilli(1_700_000_000_000L)); + javaBean.setTags(Arrays.asList("a", "b", "c", "d")); + javaBean.setCounts(new HashMap<>(attrs)); + javaBeanIn = encodeToStream(javaBeanCoder, javaBean); + } + + private static ResettableByteArrayInputStream encodeToStream(Coder coder, T value) + throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(256); + coder.encode(value, baos); + return new ResettableByteArrayInputStream(baos.toByteArray()); + } + } + + @Benchmark + public int rowCoderFlatEncode(CoderState s) throws IOException { + s.out.reset(); + s.flatCoder.encode(s.flatRow, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public Row rowCoderFlatDecode(CoderState s) throws IOException { + s.flatIn.rewind(); + return s.flatCoder.decode(s.flatIn); + } + + @Benchmark + public long rowCoderFlatByteSize(CoderState s) throws Exception { + s.flatCoder.registerByteSizeObserver(s.flatRow, s.observer); + return s.observer.resetAndAdvance(); + } + + @Benchmark + public int rowCoderStaticEncode(CoderState s) throws IOException { + s.out.reset(); + s.staticCoder.encode(s.staticRow, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public Row rowCoderStaticDecode(CoderState s) throws IOException { + s.staticIn.rewind(); + return s.staticCoder.decode(s.staticIn); + } + + @Benchmark + public int rowCoderNullableNoNullsEncode(CoderState s) throws IOException { + s.out.reset(); + s.nullableCoder.encode(s.nullableNoNullsRow, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public Row rowCoderNullableNoNullsDecode(CoderState s) throws IOException { + s.nullableNoNullsIn.rewind(); + return s.nullableCoder.decode(s.nullableNoNullsIn); + } + + @Benchmark + public int rowCoderNullableSparseEncode(CoderState s) throws IOException { + s.out.reset(); + s.nullableCoder.encode(s.nullableSparseNullsRow, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public Row rowCoderNullableSparseDecode(CoderState s) throws IOException { + s.nullableSparseNullsIn.rewind(); + return s.nullableCoder.decode(s.nullableSparseNullsIn); + } + + @Benchmark + public int rowCoderWide40Encode(CoderState s) throws IOException { + s.out.reset(); + s.wideCoder.encode(s.wideRow, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public Row rowCoderWide40Decode(CoderState s) throws IOException { + s.wideIn.rewind(); + return s.wideCoder.decode(s.wideIn); + } + + @Benchmark + public int rowCoderNestedEncode(CoderState s) throws IOException { + s.out.reset(); + s.nestedCoder.encode(s.nestedRow, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public Row rowCoderNestedDecode(CoderState s) throws IOException { + s.nestedIn.rewind(); + return s.nestedCoder.decode(s.nestedIn); + } + + @Benchmark + public int rowCoderLogicalTypesEncode(CoderState s) throws IOException { + s.out.reset(); + s.logicalCoder.encode(s.logicalRow, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public Row rowCoderLogicalTypesDecode(CoderState s) throws IOException { + s.logicalIn.rewind(); + return s.logicalCoder.decode(s.logicalIn); + } + + @Benchmark + public long rowCoderLazyIterableByteSize(CoderState s) throws Exception { + s.groupedOutputCoder.registerByteSizeObserver(s.groupedOutputRow, s.observer); + boolean lazy = s.observer.getIsLazy(); + long size = s.observer.resetAndAdvance(); + return lazy ? 1L : size; + } + + @Benchmark + public int schemaCoderFlatPojoEncode(CoderState s) throws IOException { + s.out.reset(); + s.flatPojoCoder.encode(s.flatPojo, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public FlatPojo schemaCoderFlatPojoDecode(CoderState s) throws IOException { + s.flatPojoIn.rewind(); + return s.flatPojoCoder.decode(s.flatPojoIn); + } + + @Benchmark + public int schemaCoderRichPojoEncode(CoderState s) throws IOException { + s.out.reset(); + s.richPojoCoder.encode(s.richPojo, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public RichPojo schemaCoderRichPojoDecode(CoderState s) throws IOException { + s.richPojoIn.rewind(); + return s.richPojoCoder.decode(s.richPojoIn); + } + + @Benchmark + public int schemaCoderJavaBeanEncode(CoderState s) throws IOException { + s.out.reset(); + s.javaBeanCoder.encode(s.javaBean, s.out); + return s.out.writtenSize(); + } + + @Benchmark + public FlatJavaBean schemaCoderJavaBeanDecode(CoderState s) throws IOException { + s.javaBeanIn.rewind(); + return s.javaBeanCoder.decode(s.javaBeanIn); + } +} diff --git a/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaTransformsBenchmark.java b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaTransformsBenchmark.java new file mode 100644 index 000000000000..ce7da9147beb --- /dev/null +++ b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/schemas/SchemaTransformsBenchmark.java @@ -0,0 +1,290 @@ +/* + * 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.beam.sdk.jmh.schemas; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.Pipeline.PipelineVisitor; +import org.apache.beam.sdk.runners.TransformHierarchy.Node; +import org.apache.beam.sdk.schemas.FieldAccessDescriptor; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.transforms.Cast; +import org.apache.beam.sdk.schemas.transforms.Group; +import org.apache.beam.sdk.schemas.utils.RowSelector; +import org.apache.beam.sdk.schemas.utils.SelectHelpers; +import org.apache.beam.sdk.transforms.Combine; +import org.apache.beam.sdk.transforms.Combine.CombineFn; +import org.apache.beam.sdk.transforms.Count; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.Max; +import org.apache.beam.sdk.transforms.Min; +import org.apache.beam.sdk.transforms.Sum; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.Row; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +/** + * JMH benchmarks for schema transform steady-state execution paths ({@link RowSelector} / {@link + * SelectHelpers}, {@link Group} {@code SchemaAggregateFn}, and {@link Cast#castRow}). + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) +@Fork(1) +@SuppressWarnings({"nullness", "rawtypes", "unchecked"}) +public class SchemaTransformsBenchmark { + + @State(Scope.Thread) + public static class TransformState { + Schema wideSchema; + Row wideRow; + RowSelector wildcardSelector; + RowSelector flatSubsetSelector; + + Schema nestedContainerSchema; + Row nestedContainerRow; + RowSelector listProjectSelector; + RowSelector mapProjectSelector; + + Schema aggInputSchema; + Row[] aggInputRows; + CombineFn flat4AggFn; + + Schema castInputSchema; + Schema castIdenticalSchema; + Schema castWidenedSchema; + Row castRow; + + @Setup + public void setUp() { + Schema.Builder wb = Schema.builder(); + Object[] wv = new Object[30]; + for (int i = 0; i < 30; i++) { + if (i % 3 == 0) { + wb.addInt64Field("l_" + i); + wv[i] = 100L + i; + } else if (i % 3 == 1) { + wb.addDoubleField("d_" + i); + wv[i] = 1.5 * i; + } else { + wb.addStringField("s_" + i); + wv[i] = "str_" + i; + } + } + wideSchema = wb.build(); + wideRow = Row.withSchema(wideSchema).addValues(wv).build(); + wildcardSelector = + SelectHelpers.getRowSelectorOptimized( + wideSchema, FieldAccessDescriptor.withAllFields().resolve(wideSchema)); + flatSubsetSelector = + SelectHelpers.getRowSelectorOptimized( + wideSchema, + FieldAccessDescriptor.withFieldNames("l_0", "d_1", "s_2").resolve(wideSchema)); + + Schema elemSchema = + Schema.builder() + .addStringField("a") + .addInt64Field("b") + .addDoubleField("c") + .addBooleanField("d") + .build(); + nestedContainerSchema = + Schema.builder() + .addInt64Field("id") + .addArrayField("items", FieldType.row(elemSchema)) + .addMapField("entries", FieldType.STRING, FieldType.row(elemSchema)) + .build(); + List items = new ArrayList<>(16); + Map entries = new HashMap<>(); + for (int i = 0; i < 16; i++) { + Row r = + Row.withSchema(elemSchema).addValues("n" + i, (long) i, i * 2.5, i % 2 == 0).build(); + items.add(r); + entries.put("k" + i, r); + } + nestedContainerRow = + Row.withSchema(nestedContainerSchema).addValues(1L, items, entries).build(); + listProjectSelector = + SelectHelpers.getRowSelectorOptimized( + nestedContainerSchema, + FieldAccessDescriptor.withFieldNames("items.a", "items.b", "items.c") + .resolve(nestedContainerSchema)); + mapProjectSelector = + SelectHelpers.getRowSelectorOptimized( + nestedContainerSchema, + FieldAccessDescriptor.withFieldNames("entries.a", "entries.b", "entries.c") + .resolve(nestedContainerSchema)); + + aggInputSchema = + Schema.builder() + .addStringField("userId") + .addStringField("country") + .addInt64Field("cost") + .addDoubleField("duration") + .addStringField("payload") + .build(); + aggInputRows = new Row[16]; + for (int i = 0; i < aggInputRows.length; i++) { + aggInputRows[i] = + Row.withSchema(aggInputSchema) + .addValues("user-1", "US", 10L * (i + 1), 1.5 * (i + 1), "extra-payload-" + i) + .build(); + } + flat4AggFn = extractSchemaAggregateFn(aggInputSchema); + + Schema childIn = Schema.builder().addStringField("sku").addInt32Field("qty").build(); + Schema childWide = Schema.builder().addStringField("sku").addInt64Field("qty").build(); + castInputSchema = + Schema.builder() + .addInt32Field("id") + .addStringField("name") + .addRowField("child", childIn) + .addArrayField("tags", FieldType.STRING) + .addMapField("counts", FieldType.STRING, FieldType.INT32) + .build(); + castIdenticalSchema = + Schema.builder() + .addInt32Field("id") + .addStringField("name") + .addRowField("child", childIn) + .addArrayField("tags", FieldType.STRING) + .addMapField("counts", FieldType.STRING, FieldType.INT32) + .build(); + castWidenedSchema = + Schema.builder() + .addInt64Field("id") + .addStringField("name") + .addRowField("child", childWide) + .addArrayField("tags", FieldType.STRING) + .addMapField("counts", FieldType.STRING, FieldType.INT64) + .build(); + List tags = new ArrayList<>(8); + Map counts = new HashMap<>(); + for (int i = 0; i < 8; i++) { + tags.add("tag-" + i); + counts.put("k" + i, i); + } + castRow = + Row.withSchema(castInputSchema) + .addValues( + 42, "alice", Row.withSchema(childIn).addValues("sku-1", 5).build(), tags, counts) + .build(); + } + + private static CombineFn extractSchemaAggregateFn(Schema schema) { + Pipeline p = Pipeline.create(); + PCollection input = + p.apply(Create.empty(org.apache.beam.sdk.coders.RowCoder.of(schema))) + .setRowSchema(schema); + input.apply( + Group.byFieldNames("userId", "country") + .aggregateField("cost", Sum.ofLongs(), "total_cost") + .aggregateField("cost", Min.ofLongs(), "min_cost") + .aggregateField("cost", Max.ofLongs(), "max_cost") + .aggregateField("cost", Count.combineFn(), "bid_count") + .aggregateField("duration", Sum.ofDoubles(), "total_duration")); + AtomicReference> found = new AtomicReference<>(); + p.traverseTopologically( + new PipelineVisitor.Defaults() { + @Override + public CompositeBehavior enterCompositeTransform(Node node) { + if (node.getTransform() instanceof Combine.PerKey) { + Combine.PerKey perKey = (Combine.PerKey) node.getTransform(); + found.set((CombineFn) perKey.getFn()); + } + return CompositeBehavior.ENTER_TRANSFORM; + } + }); + if (found.get() == null) { + throw new IllegalStateException("Could not find SchemaAggregateFn inside Group transform"); + } + return found.get(); + } + } + + @Benchmark + public Row rowSelectorWildcard30(TransformState s) { + return s.wildcardSelector.select(s.wideRow); + } + + @Benchmark + public Row rowSelectorSubset3Of30(TransformState s) { + return s.flatSubsetSelector.select(s.wideRow); + } + + @Benchmark + public Row rowSelectorNestedList16(TransformState s) { + return s.listProjectSelector.select(s.nestedContainerRow); + } + + @Benchmark + public Row rowSelectorNestedMap16(TransformState s) { + return s.mapProjectSelector.select(s.nestedContainerRow); + } + + @Benchmark + public Row schemaAggregateFn16Rows(TransformState s) { + Object acc = s.flat4AggFn.createAccumulator(); + for (Row r : s.aggInputRows) { + acc = s.flat4AggFn.addInput(acc, r); + } + return s.flat4AggFn.extractOutput(acc); + } + + /** + * Benchmarks creating 4 single-row accumulators and merging them via {@code mergeAccumulators} + * (measures create + 4x addInput + mergeAccumulators to avoid mutating shared state in-place). + */ + @Benchmark + public Object schemaAggregateFnMerge4(TransformState s) { + // Re-create accumulators to avoid mutating shared benchmark state in-place across iterations. + List fresh = new ArrayList<>(4); + for (int i = 0; i < 4; i++) { + Object acc = s.flat4AggFn.createAccumulator(); + acc = s.flat4AggFn.addInput(acc, s.aggInputRows[i]); + fresh.add(acc); + } + return s.flat4AggFn.mergeAccumulators(fresh); + } + + @Benchmark + public Row castRowIdenticalSchema(TransformState s) { + return Cast.castRow(s.castRow, s.castInputSchema, s.castIdenticalSchema); + } + + @Benchmark + public Row castRowWidenedSchema(TransformState s) { + return Cast.castRow(s.castRow, s.castInputSchema, s.castWidenedSchema); + } +} diff --git a/sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/schemas/SchemaOptimizationBenchmarksTest.java b/sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/schemas/SchemaOptimizationBenchmarksTest.java new file mode 100644 index 000000000000..3518edac7913 --- /dev/null +++ b/sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/schemas/SchemaOptimizationBenchmarksTest.java @@ -0,0 +1,127 @@ +/* + * 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.beam.sdk.jmh.schemas; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertTrue; + +import org.apache.beam.sdk.jmh.schemas.RowAndSchemaBenchmark.RowState; +import org.apache.beam.sdk.jmh.schemas.SchemaCoderBenchmark.CoderState; +import org.apache.beam.sdk.jmh.schemas.SchemaTransformsBenchmark.TransformState; +import org.apache.beam.sdk.values.Row; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.openjdk.jmh.infra.Blackhole; + +/** + * Smoke tests verifying all schema JMH benchmark methods run cleanly and return expected output. + */ +@RunWith(JUnit4.class) +public class SchemaOptimizationBenchmarksTest { + + @Test + public void testSchemaCoderBenchmark() throws Exception { + SchemaCoderBenchmark bench = new SchemaCoderBenchmark(); + CoderState s = new CoderState(); + s.setUp(); + + assertThat(bench.rowCoderFlatEncode(s), greaterThan(0)); + assertThat(bench.rowCoderFlatDecode(s), equalTo(s.flatRow)); + assertThat(bench.rowCoderFlatByteSize(s), greaterThan(0L)); + assertThat(bench.rowCoderStaticEncode(s), greaterThan(0)); + assertThat(bench.rowCoderStaticDecode(s), equalTo(s.staticRow)); + assertThat(bench.rowCoderNullableNoNullsEncode(s), greaterThan(0)); + assertThat(bench.rowCoderNullableNoNullsDecode(s), equalTo(s.nullableNoNullsRow)); + assertThat(bench.rowCoderNullableSparseEncode(s), greaterThan(0)); + assertThat(bench.rowCoderNullableSparseDecode(s), equalTo(s.nullableSparseNullsRow)); + assertThat(bench.rowCoderWide40Encode(s), greaterThan(0)); + assertThat(bench.rowCoderWide40Decode(s), equalTo(s.wideRow)); + assertThat(bench.rowCoderNestedEncode(s), greaterThan(0)); + assertThat(bench.rowCoderNestedDecode(s), equalTo(s.nestedRow)); + assertThat(bench.rowCoderLogicalTypesEncode(s), greaterThan(0)); + assertThat(bench.rowCoderLogicalTypesDecode(s), equalTo(s.logicalRow)); + assertThat(bench.rowCoderLazyIterableByteSize(s), equalTo(1L)); + assertThat(bench.schemaCoderFlatPojoEncode(s), greaterThan(0)); + assertThat(bench.schemaCoderFlatPojoDecode(s).fString1, equalTo("us-central1")); + assertThat(bench.schemaCoderRichPojoEncode(s), greaterThan(0)); + assertThat(bench.schemaCoderRichPojoDecode(s).name, equalTo("widget")); + assertThat(bench.schemaCoderJavaBeanEncode(s), greaterThan(0)); + assertThat(bench.schemaCoderJavaBeanDecode(s).getFString1(), equalTo("us-central1")); + } + + @Test + public void testRowAndSchemaBenchmark() throws Exception { + RowAndSchemaBenchmark bench = new RowAndSchemaBenchmark(); + RowState s = new RowState(); + s.setUp(); + + Blackhole bh = + new Blackhole( + "Today's password is swordfish. I understand instantiating Blackholes directly is dangerous."); + assertTrue(bench.rowEqualsDifferentSchemaUuid(s)); + assertThat(bench.rowHashCode(s), equalTo(s.rowStorageA.hashCode())); + assertThat(bench.rowGetDateTime(s), notNullValue()); + assertThat(bench.rowGetBaseValues(s).size(), equalTo(7)); + bench.rowWithGettersCachedCollectionRead(s, bh); + bench.rowWithGettersFreshReadAll(s, bh); + assertThat(bench.rowWithGettersNestedRowRead(s), equalTo("Seattle")); + assertThat(bench.flatPojoFromRow(s).fString1, equalTo("alpha")); + assertThat(bench.richPojoFromRow(s).name, equalTo("widget")); + assertThat(bench.javaBeanFromRow(s).getFString1(), equalTo("alpha")); + assertTrue(bench.schemaEqualsDifferentUuid(s)); + assertTrue(bench.schemaEquivalent(s)); + assertThat(bench.schemaNameOf(s), equalTo("amount")); + assertThat(bench.schemaGetFieldNames(s).size(), equalTo(7)); + bench.typeNamePredicates(s); + assertThat(bench.rowMessagesToBytes(s).length, greaterThan(0)); + assertThat(bench.jsonRowToBytes(s).length, greaterThan(0)); + assertThat(bench.jsonBytesToRow(s), equalTo(s.jsonRow)); + assertThat(bench.logicalTimestampToInput(s), equalTo(s.javaInstant)); + assertThat(bench.logicalTimestampToBase(s).getFieldCount(), equalTo(2)); + assertThat(bench.logicalDateTimeToInput(s), equalTo(s.ldt)); + assertThat(bench.logicalDateTimeToBase(s).getFieldCount(), equalTo(2)); + assertThat(bench.logicalUuidToInput(s), equalTo(s.uuid)); + assertThat(bench.logicalUuidToBase(s).getFieldCount(), equalTo(2)); + assertThat(bench.logicalEnumValueOf(s).getValue(), equalTo(2)); + assertThat(bench.logicalOneOfToInput(s), equalTo(s.oneOfVal)); + assertThat(bench.logicalOneOfToBase(s).getFieldCount(), equalTo(4)); + assertThat(bench.logicalFixedNumericToInput(s), equalTo(s.numericVal)); + } + + @Test + public void testSchemaTransformsBenchmark() { + SchemaTransformsBenchmark bench = new SchemaTransformsBenchmark(); + TransformState s = new TransformState(); + s.setUp(); + + assertThat(bench.rowSelectorWildcard30(s).getFieldCount(), equalTo(30)); + assertThat(bench.rowSelectorSubset3Of30(s).getFieldCount(), equalTo(3)); + assertThat(bench.rowSelectorNestedList16(s).getFieldCount(), equalTo(3)); + assertThat(bench.rowSelectorNestedMap16(s).getFieldCount(), equalTo(3)); + Row agg = bench.schemaAggregateFn16Rows(s); + assertThat(agg.getInt64("total_cost"), equalTo(1360L)); + assertThat(agg.getInt64("bid_count"), equalTo(16L)); + assertThat(bench.schemaAggregateFnMerge4(s), notNullValue()); + assertThat(bench.castRowIdenticalSchema(s).getFieldCount(), equalTo(5)); + assertThat(bench.castRowWidenedSchema(s).getInt64("id"), equalTo(42L)); + } +}