From 898f2ca117c976f9e9f3acebb2911c1f889dd255 Mon Sep 17 00:00:00 2001 From: chaokunyang Date: Fri, 4 Dec 2026 14:14:36 +0800 Subject: [PATCH 1/2] fix(protocol): refine Fory 2.0 Go enum/union, JS identity checks, Java native layer alignment, and Swift union skip --- benchmarks/go/models.go | 4 + compiler/fory_compiler/generators/go.py | 15 ++ .../tests/test_fory_2_0_codegen.py | 3 + go/fory/enum.go | 21 ++- go/fory/field_info.go | 18 ++- go/fory/field_spec.go | 3 + go/fory/fory_2_0_test.go | 146 ++++++++++++++++++ go/fory/type_def.go | 3 + go/fory/type_resolver.go | 137 +++++++++++++++- go/fory/union.go | 8 +- .../java/org/apache/fory/meta/TypeDef.java | 122 ++++++++++----- .../apache/fory/Fory20UnregisteredTest.java | 93 +++++++++++ javascript/packages/core/lib/context.ts | 93 ++++++++++- javascript/packages/core/lib/gen/builder.ts | 21 ++- javascript/packages/core/lib/gen/enum.ts | 21 ++- javascript/packages/core/lib/gen/ext.ts | 21 ++- javascript/packages/core/lib/gen/struct.ts | 21 ++- javascript/packages/core/lib/gen/union.ts | 21 ++- javascript/test/fory2.test.ts | 87 +++++++++++ swift/Sources/Fory/FieldSkipper.swift | 2 +- swift/Sources/Fory/ReadContext.swift | 13 +- swift/Sources/Fory/TypeResolver.swift | 24 +++ swift/Tests/ForyTests/Fory20Tests.swift | 72 +++++++++ 23 files changed, 893 insertions(+), 76 deletions(-) diff --git a/benchmarks/go/models.go b/benchmarks/go/models.go index cb4e5c0c5b..920449db79 100644 --- a/benchmarks/go/models.go +++ b/benchmarks/go/models.go @@ -104,6 +104,8 @@ type SampleV2 struct { // Player enum type type Player int32 +func (Player) ForyEnumMarker() {} + const ( PlayerJava Player = 0 PlayerFlash Player = 1 @@ -112,6 +114,8 @@ const ( // Size enum type type Size int32 +func (Size) ForyEnumMarker() {} + const ( SizeSmall Size = 0 SizeLarge Size = 1 diff --git a/compiler/fory_compiler/generators/go.py b/compiler/fory_compiler/generators/go.py index f5fd66c6b0..9da3f42507 100644 --- a/compiler/fory_compiler/generators/go.py +++ b/compiler/fory_compiler/generators/go.py @@ -492,6 +492,8 @@ def generate_enum( const_name = f"{type_name}{self.to_pascal_case(stripped_name)}" lines.append(f"\t{const_name} {type_name} = {value.value}") lines.append(")") + lines.append("") + lines.append(f"func ({type_name}) ForyEnumMarker() {{}}") return lines @@ -617,6 +619,19 @@ def generate_union( lines.append(f"func (u {type_name}) ForyUnionMarker() {{}}") lines.append("") + cases = [] + for field in union.fields: + type_expr = self.get_union_case_reflect_type_expr(field, parent_stack) + type_id_expr = self.get_union_case_type_id_expr(field, parent_stack) + spec_expr = self.get_union_case_type_spec_expr(field, parent_stack) + spec_field = f", Spec: {spec_expr}" if spec_expr is not None else "" + cases.append( + f"fory.UnionCase{{ID: {field.number}, Type: {type_expr}, TypeID: {type_id_expr}{spec_field}}}" + ) + lines.append(f"func (u {type_name}) ForyUnionCases() []fory.UnionCase {{") + lines.append(f"\treturn []fory.UnionCase{{{', '.join(cases)}}}") + lines.append("}") + lines.append("") lines.append( f"func (u {type_name}) ForyUnionGet() (uint32, any) {{ return uint32(u.case_), u.value }}" ) diff --git a/compiler/fory_compiler/tests/test_fory_2_0_codegen.py b/compiler/fory_compiler/tests/test_fory_2_0_codegen.py index 00cb7e6743..649aa15831 100644 --- a/compiler/fory_compiler/tests/test_fory_2_0_codegen.py +++ b/compiler/fory_compiler/tests/test_fory_2_0_codegen.py @@ -85,6 +85,9 @@ def test_go_generator_uses_fory_2_0_type_ids(): assert "fory.NAMED_ENUM" in content assert "fory.TYPED_STRUCT" in content assert "fory.NAMED_STRUCT" in content + assert "func (Color) ForyEnumMarker() {}" in content + assert "func (NamedColor) ForyEnumMarker() {}" in content + assert "func (u DemoUnion) ForyUnionCases() []fory.UnionCase {" in content def test_dart_generator_uses_fory_2_0_enum_type_id(): diff --git a/go/fory/enum.go b/go/fory/enum.go index 47d1b92813..2a3eb570c0 100644 --- a/go/fory/enum.go +++ b/go/fory/enum.go @@ -18,9 +18,16 @@ package fory import ( + "math" "reflect" ) +// EnumMarker marks Go numeric enum types so unregistered enums serialize as Fory ENUM +// ordinals rather than ordinary named integer types. +type EnumMarker interface { + ForyEnumMarker() +} + // enumSerializer serializes Go enum types (which are typically int-based types) // For xlang serialization, enums are written as VarUint32Small7 of their ordinal value type enumSerializer struct { @@ -33,9 +40,19 @@ func (s *enumSerializer) WriteData(ctx *WriteContext, value reflect.Value) { var ordinal uint32 switch value.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - ordinal = uint32(value.Int()) + v := value.Int() + if v < 0 || v > math.MaxUint32 { + ctx.SetError(SerializationErrorf("enum value %d out of uint32 ordinal range", v)) + return + } + ordinal = uint32(v) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - ordinal = uint32(value.Uint()) + v := value.Uint() + if v > math.MaxUint32 { + ctx.SetError(SerializationErrorf("enum value %d out of uint32 ordinal range", v)) + return + } + ordinal = uint32(v) default: ctx.SetError(SerializationErrorf("enum serializer: unsupported kind %v", value.Kind())) return diff --git a/go/fory/field_info.go b/go/fory/field_info.go index f262df851d..8845a1f353 100644 --- a/go/fory/field_info.go +++ b/go/fory/field_info.go @@ -487,9 +487,11 @@ func isInternalTypeWithoutTypeMeta(t reflect.Type) bool { } var ( - unionMarkerType = reflect.TypeOf((*UnionMarker)(nil)).Elem() - unionGetterType = reflect.TypeOf((*UnionGetter)(nil)).Elem() - unionSetterType = reflect.TypeOf((*UnionSetter)(nil)).Elem() + enumMarkerType = reflect.TypeOf((*EnumMarker)(nil)).Elem() + unionMarkerType = reflect.TypeOf((*UnionMarker)(nil)).Elem() + unionGetterType = reflect.TypeOf((*UnionGetter)(nil)).Elem() + unionSetterType = reflect.TypeOf((*UnionSetter)(nil)).Elem() + unionDescriptorType = reflect.TypeOf((*UnionDescriptor)(nil)).Elem() ) // isUnionType checks if a type implements the union accessors. @@ -997,13 +999,17 @@ func isBuiltinPrimitiveElem(t reflect.Type) bool { return t.PkgPath() == "" || t == float16Type || t == bfloat16Type } -// isUnregisteredEnumType reports whether t is a user-defined named integer type -// (the idiomatic Go enum representation) that is not a built-in numeric alias. +// isUnregisteredEnumType reports whether t is a user-defined numeric type explicitly marked +// as a Fory enum via EnumMarker. Ordinary named integer types such as `type Balance int64` +// are not enums and preserve their underlying scalar integer encoding and full value range. func isUnregisteredEnumType(t reflect.Type) bool { if t == nil || t.PkgPath() == "" || t == durationType || t == float16Type || t == bfloat16Type { return false } - return isNumericKind(t.Kind()) + if !isNumericKind(t.Kind()) { + return false + } + return t.Implements(enumMarkerType) || reflect.PtrTo(t).Implements(enumMarkerType) } // typeIdFromKind derives a TypeId from a reflect.Type's kind diff --git a/go/fory/field_spec.go b/go/fory/field_spec.go index 32bdf8d4c5..4a982a092d 100644 --- a/go/fory/field_spec.go +++ b/go/fory/field_spec.go @@ -919,6 +919,9 @@ func inferPackedElementTypeSpec(goType reflect.Type) (*TypeSpec, bool) { if goType == durationType { return NewSimpleTypeSpec(DURATION), true } + if !isBuiltinPrimitiveElem(goType) { + return nil, false + } switch goType.Kind() { case reflect.Bool: return NewSimpleTypeSpec(BOOL), true diff --git a/go/fory/fory_2_0_test.go b/go/fory/fory_2_0_test.go index dc24b8e275..8013d718ac 100644 --- a/go/fory/fory_2_0_test.go +++ b/go/fory/fory_2_0_test.go @@ -49,11 +49,25 @@ type f20NestedLeaf struct { type f20Role int32 +func (f20Role) ForyEnumMarker() {} + const ( f20RoleUser f20Role = iota f20RoleAdmin ) +type f20Balance int64 +type f20Counter uint64 + +type f20NamedIntAndEnum struct { + PosBalance f20Balance + NegBalance f20Balance + BigCounter f20Counter + Role f20Role + BalanceList []f20Balance + RoleList []f20Role +} + type f20NestedContainer struct { Leaf f20NestedLeaf LeafPtr *f20NestedLeaf @@ -124,6 +138,26 @@ func (u *f20UnionCase) ForyUnionSet(caseID uint32, value any) { u.value = value } +type f20UnboundUnion struct { + caseID uint32 + value any +} + +func (f20UnboundUnion) ForyUnionMarker() {} +func (u f20UnboundUnion) ForyUnionGet() (uint32, any) { + return u.caseID, u.value +} +func (u *f20UnboundUnion) ForyUnionSet(caseID uint32, value any) { + u.caseID = caseID + u.value = value +} +func (f20UnboundUnion) ForyUnionCases() []UnionCase { + return []UnionCase{ + {ID: 0, Type: reflect.TypeOf(int32(0)), TypeID: VARINT32}, + {ID: 1, Type: reflect.TypeOf(f20NestedLeaf{}), TypeID: COMPATIBLE_STRUCT}, + } +} + func TestFory20RootHeaderVersionAndValidation(t *testing.T) { fx := New(WithXlang(true), WithCompatible(false)) dataX, err := fx.Serialize(int32(42)) @@ -491,3 +525,115 @@ func TestFory20UnboundMetaBackRefDistinctTargetsAfterL0Hit(t *testing.T) { require.Equal(t, f20Point2D{X: 10, Y: 20}, out.P) require.Equal(t, f20Vector2D{X: 30, Y: 40}, out.V) } + +func TestFory20NamedIntegersPreserveRangeAlongsideUnregisteredEnum(t *testing.T) { + for _, compatible := range []bool{true, false} { + writer := New(WithXlang(true), WithCompatible(compatible)) + reader := New(WithXlang(true), WithCompatible(compatible)) + + orig := f20NamedIntAndEnum{ + PosBalance: f20Balance(1 << 40), + NegBalance: f20Balance(-1), + BigCounter: f20Counter((uint64(1) << 50) + 12345), + Role: f20RoleAdmin, + BalanceList: []f20Balance{f20Balance(-(1 << 45)), f20Balance(-1), f20Balance(1 << 42)}, + RoleList: []f20Role{f20RoleUser, f20RoleAdmin}, + } + data, err := writer.Serialize(&orig) + require.NoError(t, err) + + var out f20NamedIntAndEnum + require.NoError(t, reader.Deserialize(bytes.Clone(data), &out)) + require.Equal(t, orig, out) + + // Verify root round-trips and wire type IDs distinguish named integers from marked enums. + bal := f20Balance(1 << 40) + balBytes, err := writer.Serialize(bal) + require.NoError(t, err) + require.Equal(t, uint8(VARINT64), balBytes[2]) + var balOut f20Balance + require.NoError(t, reader.Deserialize(bytes.Clone(balBytes), &balOut)) + require.Equal(t, bal, balOut) + + negBal := f20Balance(-1) + negBytes, err := writer.Serialize(negBal) + require.NoError(t, err) + var negOut f20Balance + require.NoError(t, reader.Deserialize(bytes.Clone(negBytes), &negOut)) + require.Equal(t, negBal, negOut) + + roleBytes, err := writer.Serialize(f20RoleAdmin) + require.NoError(t, err) + require.Equal(t, uint8(ENUM), roleBytes[2]) + var roleOut f20Role + require.NoError(t, reader.Deserialize(bytes.Clone(roleBytes), &roleOut)) + require.Equal(t, f20RoleAdmin, roleOut) + + // Marked enum with out-of-range ordinal must return a controlled serialization error. + invalidRole := f20Role(-1) + _, err = writer.Serialize(invalidRole) + require.Error(t, err) + } +} + +func TestFory20UnboundUnionRoundTrip(t *testing.T) { + for _, compatible := range []bool{true, false} { + writer := New(WithXlang(true), WithCompatible(compatible)) + reader := New(WithXlang(true), WithCompatible(compatible)) + + primOrig := f20UnboundUnion{caseID: 0, value: int32(-123456)} + primBytes, err := writer.Serialize(&primOrig) + require.NoError(t, err) + // Byte 0: root header, Byte 1: ref flag, Byte 2: wire type id (UNION) + require.Equal(t, uint8(UNION), primBytes[2]) + + var primOut f20UnboundUnion + require.NoError(t, reader.Deserialize(bytes.Clone(primBytes), &primOut)) + require.Equal(t, primOrig, primOut) + + structOrig := f20UnboundUnion{ + caseID: 1, + value: f20NestedLeaf{Label: "unbound-union-leaf", Score: 99}, + } + structBytes, err := writer.Serialize(&structOrig) + require.NoError(t, err) + require.Equal(t, uint8(UNION), structBytes[2]) + + var structOut f20UnboundUnion + require.NoError(t, reader.Deserialize(bytes.Clone(structBytes), &structOut)) + require.Equal(t, structOrig, structOut) + + // Dynamic any read must reject an UNBOUND UNION with no registered identity. + var dynOut any + require.Error(t, reader.Deserialize(bytes.Clone(structBytes), &dynOut)) + + // Struct holding an unregistered union field must also round-trip cleanly. + type unionHolder struct { + Tag string + Value f20UnboundUnion + } + holderOrig := unionHolder{Tag: "holder", Value: structOrig} + holderBytes, err := writer.Serialize(&holderOrig) + require.NoError(t, err) + var holderOut unionHolder + require.NoError(t, reader.Deserialize(bytes.Clone(holderBytes), &holderOut)) + require.Equal(t, holderOrig, holderOut) + } + + // Asymmetric: registered union writer -> unregistered UnionDescriptor reader. + regWriter := New(WithXlang(true), WithCompatible(true)) + require.NoError(t, regWriter.RegisterUnion( + f20UnboundUnion{}, + 812, + NewUnionSerializer(f20UnboundUnion{}.ForyUnionCases()...), + )) + unregReader := New(WithXlang(true), WithCompatible(true)) + asymOrig := f20UnboundUnion{caseID: 1, value: f20NestedLeaf{Label: "asym-union", Score: 55}} + asymBytes, err := regWriter.Serialize(&asymOrig) + require.NoError(t, err) + require.Equal(t, uint8(TYPED_UNION), asymBytes[2]) + + var asymOut f20UnboundUnion + require.NoError(t, unregReader.Deserialize(bytes.Clone(asymBytes), &asymOut)) + require.Equal(t, asymOrig, asymOut) +} diff --git a/go/fory/type_def.go b/go/fory/type_def.go index 839c5a862a..fe5c281d54 100644 --- a/go/fory/type_def.go +++ b/go/fory/type_def.go @@ -387,6 +387,9 @@ func (td *TypeDef) buildTypeInfoForTarget(resolver *TypeResolver, targetType ref localInfo.Serializer != nil && isUnionTypeId(TypeId(localInfo.TypeID)) { return localInfo, nil } + if localInfo, unionErr := resolver.getOrCreateLocalUnionTypeInfo(targetType); unionErr == nil && localInfo != nil { + return localInfo, nil + } } return nil, DeserializationErrorf("wire type NAMED_UNION cannot be materialized as %v", targetType) default: diff --git a/go/fory/type_resolver.go b/go/fory/type_resolver.go index d507e3b53e..be46369710 100644 --- a/go/fory/type_resolver.go +++ b/go/fory/type_resolver.go @@ -1084,6 +1084,122 @@ func (r *TypeResolver) getOrCreateLocalStructTypeInfo(type_ reflect.Type) (*Type return valInfo, nil } +func (r *TypeResolver) getOrCreateLocalUnionTypeInfo(type_ reflect.Type) (*TypeInfo, error) { + if type_ == nil { + return nil, fmt.Errorf("nil type") + } + typePtr := typePointer(type_) + if cachedInfo, ok := r.typePointerCache[typePtr]; ok && cachedInfo.Serializer != nil { + return cachedInfo, nil + } + if info, ok := r.typesInfo[type_]; ok && info.Serializer != nil { + r.typePointerCache[typePtr] = info + return info, nil + } + + isPtr := type_.Kind() == reflect.Ptr + baseType := type_ + if isPtr { + baseType = type_.Elem() + } + if baseType.Kind() != reflect.Struct || !isUnionType(baseType) { + return nil, fmt.Errorf("type %s is not a union type", type_) + } + + // If base union is already registered or cached, create matching pointer TypeInfo if needed. + if baseInfo, ok := r.typesInfo[baseType]; ok && baseInfo.Serializer != nil { + r.typePointerCache[typePointer(baseType)] = baseInfo + if !isPtr { + return baseInfo, nil + } + ptrSer, ok := r.typeToSerializers[type_] + if !ok { + ptrSer = &ptrToValueSerializer{valueSerializer: baseInfo.Serializer, valueBytes: int(baseType.Size())} + r.typeToSerializers[type_] = ptrSer + } + ptrInfo := &TypeInfo{ + Type: type_, + FullNameBytes: baseInfo.FullNameBytes, + PkgPathBytes: baseInfo.PkgPathBytes, + NameBytes: baseInfo.NameBytes, + IsDynamic: baseInfo.IsDynamic, + IsRegistered: baseInfo.IsRegistered, + IdentityKind: baseInfo.IdentityKind, + TypeID: baseInfo.TypeID, + UserTypeID: baseInfo.UserTypeID, + DispatchId: baseInfo.DispatchId, + Serializer: ptrSer, + ValueBytes: baseInfo.ValueBytes, + NeedWriteDef: baseInfo.NeedWriteDef, + NeedWriteRef: baseInfo.NeedWriteRef, + hashValue: baseInfo.hashValue, + localHeaderHash: baseInfo.localHeaderHash, + TypeDef: baseInfo.TypeDef, + } + r.typesInfo[type_] = ptrInfo + r.typePointerCache[typePtr] = ptrInfo + return ptrInfo, nil + } + + // Lazily materialize local UNBOUND metadata for an unregistered union that describes its cases. + // This does NOT mutate dynamic registries (userTypeIdToTypeInfo, namedTypeToTypeInfo, + // nsTypeToTypeInfo) and is therefore valid even after registration is frozen. + ptrType := reflect.PtrTo(baseType) + var desc UnionDescriptor + if baseType.Implements(unionDescriptorType) { + desc = reflect.Zero(baseType).Interface().(UnionDescriptor) + } else if ptrType.Implements(unionDescriptorType) { + desc = reflect.New(baseType).Interface().(UnionDescriptor) + } else { + return nil, fmt.Errorf("union type %s must implement UnionDescriptor or be registered explicitly", baseType) + } + unionSer := NewUnionSerializer(desc.ForyUnionCases()...) + if unionSer.initErr != nil { + return nil, unionSer.initErr + } + ptrSer := &ptrToValueSerializer{valueSerializer: unionSer, valueBytes: int(baseType.Size())} + + valInfo := &TypeInfo{ + Type: baseType, + TypeID: uint32(UNION), + UserTypeID: invalidUserTypeID, + IdentityKind: IdentityUnbound, + IsRegistered: false, + Serializer: unionSer, + ValueBytes: int(baseType.Size()), + IsDynamic: false, + DispatchId: GetDispatchId(baseType), + hashValue: calcTypeHash(baseType), + NeedWriteRef: NeedWriteRef(UNION), + } + ptrInfo := &TypeInfo{ + Type: ptrType, + TypeID: uint32(UNION), + UserTypeID: invalidUserTypeID, + IdentityKind: IdentityUnbound, + IsRegistered: false, + Serializer: ptrSer, + ValueBytes: int(baseType.Size()), + IsDynamic: false, + DispatchId: GetDispatchId(ptrType), + hashValue: calcTypeHash(ptrType), + NeedWriteRef: NeedWriteRef(UNION), + } + + // Publish value and pointer entries before lazy case initialization can recurse. + r.typeToSerializers[baseType] = unionSer + r.typeToSerializers[ptrType] = ptrSer + r.typesInfo[baseType] = valInfo + r.typesInfo[ptrType] = ptrInfo + r.typePointerCache[typePointer(baseType)] = valInfo + r.typePointerCache[typePointer(ptrType)] = ptrInfo + + if isPtr { + return ptrInfo, nil + } + return valInfo, nil +} + func primitiveSerializerForType(t reflect.Type) (Serializer, TypeId, bool) { if t == durationType { return durationSerializer{}, DURATION, true @@ -1182,11 +1298,14 @@ func (r *TypeResolver) getOrCreateTypeInfoByType(type_ reflect.Type) (*TypeInfo, return nil, fmt.Errorf("interface types must be registered explicitly") case reflect.Struct: if isUnionType(type_) { - return nil, fmt.Errorf("union type %s must be registered explicitly", type_) + return r.getOrCreateLocalUnionTypeInfo(type_) } return r.getOrCreateLocalStructTypeInfo(type_) case reflect.Ptr: elemType := type_.Elem() + if elemType.Kind() == reflect.Struct && isUnionType(elemType) { + return r.getOrCreateLocalUnionTypeInfo(type_) + } if elemType.Kind() == reflect.Struct && !isUnionType(elemType) && elemType != dateType && elemType != timestampType && elemType != decimalType { return r.getOrCreateLocalStructTypeInfo(type_) @@ -1454,6 +1573,13 @@ func (r *TypeResolver) getOrCreateLocalTargetTypeInfo(baseType reflect.Type) *Ty if info := r.getTypeInfoByType(baseType); info != nil { return info } + if baseType.Kind() == reflect.Struct && isUnionType(baseType) { + info, err := r.getOrCreateLocalUnionTypeInfo(baseType) + if err == nil { + return info + } + return nil + } if baseType.Kind() == reflect.Struct && !isUnionType(baseType) && baseType != dateType && baseType != timestampType && baseType != decimalType { info, err := r.getOrCreateLocalStructTypeInfo(baseType) @@ -2494,7 +2620,11 @@ func (r *TypeResolver) createSerializer(type_ reflect.Type, mapInStruct bool) (s return serializer, nil } if isUnionType(type_) { - return nil, fmt.Errorf("union type %s must be registered explicitly", type_.String()) + info, unionErr := r.getOrCreateLocalUnionTypeInfo(type_) + if unionErr != nil { + return nil, unionErr + } + return info.Serializer, nil } info, structErr := r.getOrCreateLocalStructTypeInfo(type_) if structErr != nil { @@ -2716,6 +2846,9 @@ func (r *TypeResolver) resolveAsymmetricTarget( localInfo.Serializer != nil && isUnionTypeId(TypeId(localInfo.TypeID)) { return localInfo } + if localInfo, unionErr := r.getOrCreateLocalUnionTypeInfo(baseExpected); unionErr == nil && localInfo != nil { + return localInfo + } err.SetError(DeserializationErrorf("wire union type %d cannot be materialized as %v", wireTypeID, expectedType)) return nil default: diff --git a/go/fory/union.go b/go/fory/union.go index 033ada5dfa..e9fdf8283f 100644 --- a/go/fory/union.go +++ b/go/fory/union.go @@ -39,6 +39,12 @@ type UnionSetter interface { ForyUnionSet(caseId uint32, value any) } +// UnionDescriptor supplies union case metadata so unregistered Go unions can be +// serialized and deserialized as UNBOUND UNION values without global registration. +type UnionDescriptor interface { + ForyUnionCases() []UnionCase +} + // UnionCase describes a single union alternative. type UnionCase struct { ID uint32 @@ -218,7 +224,7 @@ func (s *UnionSerializer) Read(ctx *ReadContext, refMode RefMode, readType bool, } if readType { resolver := ctx.TypeResolver() - expected := resolver.getTypeInfoByType(value.Type()) + expected := resolver.getOrCreateLocalTargetTypeInfo(value.Type()) if expected == nil { ctx.SetError(DeserializationErrorf("unregistered union type: %v", value.Type())) return diff --git a/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java b/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java index f809e69d77..d0f4b26447 100644 --- a/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java +++ b/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java @@ -26,7 +26,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.IdentityHashMap; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -556,43 +555,74 @@ private List buildDescriptors( fieldIdToDescriptorMap.put(fieldId, descriptor); } } - Map unboundRemoteLayerIndex = null; + Map unboundLayerAlignments = null; List localLayerNames = null; - Map> localDescriptorsBySimpleName = null; IdentityHashMap matchedUnboundDescriptors = null; if (!isXlang) { + boolean hasUnboundLayer = false; for (FieldInfo fi : fieldsInfo) { if (fi.getDefinedClass().startsWith(UNBOUND_LAYER_PREFIX)) { - if (unboundRemoteLayerIndex == null) { - unboundRemoteLayerIndex = new LinkedHashMap<>(); - } - unboundRemoteLayerIndex.putIfAbsent(fi.getDefinedClass(), unboundRemoteLayerIndex.size()); + hasUnboundLayer = true; + break; } } - if (unboundRemoteLayerIndex != null) { + if (hasUnboundLayer) { + List remoteLayers = new ArrayList<>(); + for (FieldInfo fi : fieldsInfo) { + String dc = fi.getDefinedClass(); + if (remoteLayers.isEmpty() || !remoteLayers.get(remoteLayers.size() - 1).equals(dc)) { + remoteLayers.add(dc); + } + } Map declaringClassSet = new HashMap<>(); for (Descriptor d : fieldDescriptors) { declaringClassSet.put(d.getDeclaringClass(), Boolean.TRUE); } localLayerNames = new ArrayList<>(); + Map localLayerIndexMap = new HashMap<>(); for (Class clz : ReflectionUtils.getAllClasses(cls, true)) { if (declaringClassSet.containsKey(clz.getName())) { + localLayerIndexMap.put(clz.getName(), localLayerNames.size()); localLayerNames.add(clz.getName()); } } if (localLayerNames.isEmpty()) { + localLayerIndexMap.put(cls.getName(), 0); localLayerNames.add(cls.getName()); } - localDescriptorsBySimpleName = new HashMap<>(); - // Store closest-to-leaf first so fallback resolves child fields before shadowed super - // fields when inheritance depth evolved. - for (int idx = localLayerNames.size() - 1; idx >= 0; idx--) { - String layerName = localLayerNames.get(idx); - for (Descriptor d : fieldDescriptors) { - if (d.getDeclaringClass().equals(layerName)) { - localDescriptorsBySimpleName - .computeIfAbsent(d.getName(), k -> new ArrayList<>()) - .add(d); + // Align the full remote layer sequence against local layers using registered/named layers + // as monotonic anchors so anonymous layers between anchors stay bound to their own segment. + int remoteCount = remoteLayers.size(); + int localCount = localLayerNames.size(); + List anchors = new ArrayList<>(); + anchors.add(new int[] {-1, -1}); + int prevLocalAnchor = -1; + for (int r = 0; r < remoteCount; r++) { + String remoteLayer = remoteLayers.get(r); + if (!remoteLayer.startsWith(UNBOUND_LAYER_PREFIX)) { + Integer localIdx = localLayerIndexMap.get(remoteLayer); + if (localIdx != null && localIdx > prevLocalAnchor) { + anchors.add(new int[] {r, localIdx}); + prevLocalAnchor = localIdx; + } + } + } + anchors.add(new int[] {remoteCount, localCount}); + unboundLayerAlignments = new HashMap<>(); + for (int a = 0; a < anchors.size() - 1; a++) { + int rStart = anchors.get(a)[0] + 1; + int rEnd = anchors.get(a + 1)[0]; + int lStart = anchors.get(a)[1] + 1; + int lEnd = anchors.get(a + 1)[1]; + int rLen = rEnd - rStart; + int lLen = lEnd - lStart; + boolean exact = rLen == lLen; + for (int r = rStart; r < rEnd; r++) { + String remoteLayer = remoteLayers.get(r); + if (remoteLayer.startsWith(UNBOUND_LAYER_PREFIX)) { + int localIdx = exact ? (lStart + (r - rStart)) : (lEnd - (rEnd - r)); + unboundLayerAlignments.put( + remoteLayer, new UnboundLayerAlignment(localIdx, lStart, lEnd, exact)); } } } @@ -617,33 +647,34 @@ private List buildDescriptors( } else { String fieldName = fieldInfo.getFieldName(); String definedClass = fieldInfo.getDefinedClass(); - if (unboundRemoteLayerIndex != null && definedClass.startsWith(UNBOUND_LAYER_PREFIX)) { - int remoteIdx = unboundRemoteLayerIndex.get(definedClass); - int remoteCount = unboundRemoteLayerIndex.size(); - int localCount = localLayerNames.size(); - int localIdx = - remoteCount == localCount ? remoteIdx : (localCount - (remoteCount - remoteIdx)); + if (unboundLayerAlignments != null && definedClass.startsWith(UNBOUND_LAYER_PREFIX)) { + UnboundLayerAlignment alignment = unboundLayerAlignments.get(definedClass); descriptor = null; - if (localIdx >= 0 && localIdx < localCount) { - Descriptor candidate = - descriptorsMap.get(localLayerNames.get(localIdx) + "." + fieldName); - if (candidate != null && !matchedUnboundDescriptors.containsKey(candidate)) { - descriptor = candidate; + if (alignment != null) { + if (alignment.localIdx >= alignment.segmentLocalStart + && alignment.localIdx < alignment.segmentLocalEnd) { + Descriptor candidate = + descriptorsMap.get(localLayerNames.get(alignment.localIdx) + "." + fieldName); + if (candidate != null && !matchedUnboundDescriptors.containsKey(candidate)) { + descriptor = candidate; + } } - } - if (descriptor == null && remoteCount != localCount) { - List candidates = localDescriptorsBySimpleName.get(fieldName); - if (candidates != null) { - for (Descriptor candidate : candidates) { - if (!matchedUnboundDescriptors.containsKey(candidate)) { + if (descriptor == null && !alignment.exactSegment) { + // Search closest-to-leaf first within the anchor-bounded local segment only. + for (int idx = alignment.segmentLocalEnd - 1; + idx >= alignment.segmentLocalStart; + idx--) { + Descriptor candidate = + descriptorsMap.get(localLayerNames.get(idx) + "." + fieldName); + if (candidate != null && !matchedUnboundDescriptors.containsKey(candidate)) { descriptor = candidate; break; } } } - } - if (descriptor != null) { - matchedUnboundDescriptors.put(descriptor, Boolean.TRUE); + if (descriptor != null) { + matchedUnboundDescriptors.put(descriptor, Boolean.TRUE); + } } } else { // Match the wire declaring-class name before any compatibility fallback attempts to @@ -817,4 +848,19 @@ public TypeDef replaceRootClassTo(TypeResolver resolver, Class targetCls) { // field matching by declaring class keeps the existing target-class semantics. return new TypeDef(classSpec, fieldInfos, id, encoded); } + + private static final class UnboundLayerAlignment { + final int localIdx; + final int segmentLocalStart; + final int segmentLocalEnd; + final boolean exactSegment; + + UnboundLayerAlignment( + int localIdx, int segmentLocalStart, int segmentLocalEnd, boolean exactSegment) { + this.localIdx = localIdx; + this.segmentLocalStart = segmentLocalStart; + this.segmentLocalEnd = segmentLocalEnd; + this.exactSegment = exactSegment; + } + } } diff --git a/java/fory-core/src/test/java/org/apache/fory/Fory20UnregisteredTest.java b/java/fory-core/src/test/java/org/apache/fory/Fory20UnregisteredTest.java index d3608b33ae..ef4230c27d 100644 --- a/java/fory-core/src/test/java/org/apache/fory/Fory20UnregisteredTest.java +++ b/java/fory-core/src/test/java/org/apache/fory/Fory20UnregisteredTest.java @@ -718,4 +718,97 @@ public void testNativeByNameStrictSkipAndAsymmetricTarget() { reader.deserialize(envelopeBytes, NativeSkipByNameReceiver.class); assertEquals(skipped.keep, 99); } + + public static class ThreeLayerBaseV1 { + public int x; + } + + public static class ThreeLayerMidV1 extends ThreeLayerBaseV1 { + public int z; + } + + public static class ThreeLayerLeafV1 extends ThreeLayerMidV1 { + public int y; + } + + public static class ThreeLayerBaseV2 { + public int x; + } + + public static class ThreeLayerMidV2 extends ThreeLayerBaseV2 { + public int z; + public int x; + } + + public static class ThreeLayerLeafV2 extends ThreeLayerMidV2 { + public int y; + } + + public static class ShadowBase { + public int x; + } + + public static class ShadowMid extends ShadowBase { + public int z; + } + + public static class ShadowLeaf extends ShadowMid { + public int x; + } + + @Test + public void testJavaNativeThreeLayerAnchorPreservesSuperFieldWithShadowing() { + for (boolean codegen : new boolean[] {true, false}) { + // V1 -> V2: Base -> Mid (registered by ID) -> Leaf, where V2 adds shadowing Mid.x. + Fory writer = + Fory.builder() + .withXlang(false) + .withCompatible(true) + .withCodegen(codegen) + .requireClassRegistration(true) + .build(); + writer.register(ThreeLayerMidV1.class, 4201); + + Fory reader = + Fory.builder() + .withXlang(false) + .withCompatible(true) + .withCodegen(codegen) + .requireClassRegistration(true) + .build(); + reader.register(ThreeLayerMidV2.class, 4201); + + ThreeLayerLeafV1 v1 = new ThreeLayerLeafV1(); + ((ThreeLayerBaseV1) v1).x = 11; + v1.z = 22; + v1.y = 33; + byte[] v1Bytes = writer.serialize(v1); + + ThreeLayerLeafV2 v2 = reader.deserialize(v1Bytes, ThreeLayerLeafV2.class); + assertEquals(((ThreeLayerBaseV2) v2).x, 11); + assertEquals(((ThreeLayerMidV2) v2).x, 0); + assertEquals(v2.z, 22); + assertEquals(v2.y, 33); + + // Unchanged 3-layer hierarchy with shadowed Base.x and Leaf.x and registered Mid. + Fory sameSchema = + Fory.builder() + .withXlang(false) + .withCompatible(true) + .withCodegen(codegen) + .requireClassRegistration(true) + .build(); + sameSchema.register(ShadowMid.class, 4202); + + ShadowLeaf src = new ShadowLeaf(); + ((ShadowBase) src).x = 101; + src.z = 202; + src.x = 303; + byte[] shadowBytes = sameSchema.serialize(src); + ShadowLeaf decoded = sameSchema.deserialize(shadowBytes, ShadowLeaf.class); + assertEquals(((ShadowBase) decoded).x, 101); + assertEquals(decoded.z, 202); + assertEquals(decoded.x, 303); + } + } } diff --git a/javascript/packages/core/lib/context.ts b/javascript/packages/core/lib/context.ts index 17b99d0d0a..a0918220f0 100644 --- a/javascript/packages/core/lib/context.ts +++ b/javascript/packages/core/lib/context.ts @@ -764,10 +764,60 @@ export class ReadContext { ); } + throwUserTypeIdMismatch( + expectedTypeId: number, + expectedUserTypeId: number, + actualUserTypeId: number, + ): never { + throw new Error( + `Type identity mismatch: expected type ${expectedTypeId} userTypeId ${expectedUserTypeId}, got userTypeId ${actualUserTypeId}`, + ); + } + + throwNamedTypeMismatch( + expectedTypeId: number, + expectedNamespace: string, + expectedTypeName: string, + actualNamespace: string, + actualTypeName: string, + ): never { + throw new Error( + `Type identity mismatch: expected named type ${expectedTypeId} ${expectedNamespace}$${expectedTypeName}, got ${actualNamespace}$${actualTypeName}`, + ); + } + + private isSameUnboundTarget(resolved: Serializer | undefined, expectedTypeInfo?: TypeInfo) { + if (resolved === undefined || expectedTypeInfo === undefined) { + return false; + } + const resolvedTypeInfo = resolved.getTypeInfo(); + if (resolvedTypeInfo.schemaOwner === expectedTypeInfo.schemaOwner) { + return true; + } + if ( + TypeId.enumType(resolvedTypeInfo.typeId) && + TypeId.enumType(expectedTypeInfo.typeId) && + resolvedTypeInfo.options?.enumProps !== undefined && + resolvedTypeInfo.options.enumProps === expectedTypeInfo.options?.enumProps + ) { + return true; + } + if ( + TypeId.extType(resolvedTypeInfo.typeId) && + TypeId.extType(expectedTypeInfo.typeId) && + resolvedTypeInfo.options?.creator !== undefined && + resolvedTypeInfo.options.creator === expectedTypeInfo.options?.creator + ) { + return true; + } + return false; + } + readAsymmetricNonEvolvingTypeInfo( wireTypeId: number, expectedTypeId: number, expectedIdentityKind: number, + expectedTypeInfo?: TypeInfo, ) { if ( wireTypeId === TypeId.COMPATIBLE_STRUCT || @@ -782,6 +832,12 @@ export class ReadContext { if (TypeId.needsUserTypeId(wireTypeId)) { const wireUserTypeId = this.reader.readVarUint32Small7(); if (expectedIdentityKind === TypeIdentityKind.UNBOUND) { + const resolved = this.typeResolver.getSerializerById(wireTypeId, wireUserTypeId); + if (resolved !== undefined && !this.isSameUnboundTarget(resolved, expectedTypeInfo)) { + throw new Error( + `Type identity mismatch: wire type ${wireTypeId} userTypeId ${wireUserTypeId} resolves to a different registered type`, + ); + } return; } throw new Error( @@ -791,10 +847,16 @@ export class ReadContext { if (TypeId.isNamedType(wireTypeId)) { if (expectedIdentityKind === TypeIdentityKind.UNBOUND) { if (this.isCompatible()) { - this.readIdentityOnlyTypeMetaForUnboundTarget(wireTypeId); + this.readIdentityOnlyTypeMetaForUnboundTarget(wireTypeId, expectedTypeInfo); } else { - this.readNamespace(); - this.readTypeName(); + const wireNs = this.readNamespace(); + const wireName = this.readTypeName(); + const resolved = this.typeResolver.getSerializerByName(`${wireNs}$${wireName}`); + if (resolved !== undefined && !this.isSameUnboundTarget(resolved, expectedTypeInfo)) { + throw new Error( + `Type identity mismatch: wire named type ${wireNs}$${wireName} resolves to a different registered type`, + ); + } } return; } @@ -805,13 +867,22 @@ export class ReadContext { this.throwUnexpectedWireTypeId(expectedTypeId, wireTypeId); } - private readIdentityOnlyTypeMetaForUnboundTarget(expectedWireTypeId: number) { + private readIdentityOnlyTypeMetaForUnboundTarget( + expectedWireTypeId: number, + expectedTypeInfo?: TypeInfo, + ) { const idOrLen = this.reader.readVarUInt32(); if (idOrLen & 1) { const typeMeta = this.readTypeMetaRef(idOrLen); if (typeMeta.getTypeId() !== expectedWireTypeId) { this.throwTypeMetaWireType(expectedWireTypeId, typeMeta.getTypeId()); } + const resolved = this.serializerByTypeMeta(typeMeta); + if (resolved !== undefined && !this.isSameUnboundTarget(resolved, expectedTypeInfo)) { + throw new Error( + `Type identity mismatch: wire named type ${typeMeta.getNs()}$${typeMeta.getTypeName()} resolves to a different registered type`, + ); + } return; } const dynamicTypeId = idOrLen >> 1; @@ -828,6 +899,12 @@ export class ReadContext { TypeMeta.skipBodyByHeaderLow(this.reader, headerLow); this.rememberTypeMeta(cachedTypeMeta); this.typeMeta.push(cachedTypeMeta); + const resolved = this.serializerByTypeMeta(cachedTypeMeta); + if (resolved !== undefined && !this.isSameUnboundTarget(resolved, expectedTypeInfo)) { + throw new Error( + `Type identity mismatch: wire named type ${cachedTypeMeta.getNs()}$${cachedTypeMeta.getTypeName()} resolves to a different registered type`, + ); + } return; } const header = (BigInt(headerHigh) << 32n) | BigInt(headerLow); @@ -853,6 +930,14 @@ export class ReadContext { } } this.typeMeta.push(typeMeta); + if ( + localSerializer !== undefined && + !this.isSameUnboundTarget(localSerializer, expectedTypeInfo) + ) { + throw new Error( + `Type identity mismatch: wire named type ${typeMeta.getNs()}$${typeMeta.getTypeName()} resolves to a different registered type`, + ); + } } private checkCompatibleTypeMetaOwner(typeMeta: TypeMeta, original?: Serializer) { diff --git a/javascript/packages/core/lib/gen/builder.ts b/javascript/packages/core/lib/gen/builder.ts index fe9d5710c2..9cee8ffd25 100644 --- a/javascript/packages/core/lib/gen/builder.ts +++ b/javascript/packages/core/lib/gen/builder.ts @@ -408,8 +408,27 @@ class TypeMetaContextBuilder { wireTypeId: string, expectedTypeId: number, expectedIdentityKind: number, + expectedTypeInfo = "typeInfo", ) { - return `${this.readHolder}.readAsymmetricNonEvolvingTypeInfo(${wireTypeId}, ${expectedTypeId}, ${expectedIdentityKind})`; + return `${this.readHolder}.readAsymmetricNonEvolvingTypeInfo(${wireTypeId}, ${expectedTypeId}, ${expectedIdentityKind}, ${expectedTypeInfo})`; + } + + throwUserTypeIdMismatch( + expectedTypeId: number, + expectedUserTypeId: number, + actualUserTypeId: string, + ) { + return `${this.readHolder}.throwUserTypeIdMismatch(${expectedTypeId}, ${expectedUserTypeId}, ${actualUserTypeId})`; + } + + throwNamedTypeMismatch( + expectedTypeId: number, + expectedNamespace: string, + expectedTypeName: string, + actualNamespace: string, + actualTypeName: string, + ) { + return `${this.readHolder}.throwNamedTypeMismatch(${expectedTypeId}, ${CodecBuilder.sourceString(expectedNamespace)}, ${CodecBuilder.sourceString(expectedTypeName)}, ${actualNamespace}, ${actualTypeName})`; } throwUnexpectedWireTypeId(expectedTypeId: number, wireTypeId?: string) { diff --git a/javascript/packages/core/lib/gen/enum.ts b/javascript/packages/core/lib/gen/enum.ts index 5d3c1c1c0f..9f01d1c574 100644 --- a/javascript/packages/core/lib/gen/enum.ts +++ b/javascript/packages/core/lib/gen/enum.ts @@ -111,16 +111,23 @@ class EnumSerializerGenerator extends BaseSerializerGenerator { } `; break; - case TypeId.TYPED_ENUM: + case TypeId.TYPED_ENUM: { + const wireUserTypeId = this.scope.uniqueName("wireUserTypeId"); bodyStmt = ` if (${wireTypeId} === ${TypeId.TYPED_ENUM}) { - ${this.builder.reader.readVarUint32Small7()}; + const ${wireUserTypeId} = ${this.builder.reader.readVarUint32Small7()}; + if (${wireUserTypeId} !== ${this.typeInfo.userTypeId}) { + ${this.builder.typeMetaResolver.throwUserTypeIdMismatch(TypeId.TYPED_ENUM, this.typeInfo.userTypeId, wireUserTypeId)}; + } } else { ${this.builder.typeMetaResolver.readAsymmetricNonEvolvingTypeInfo(wireTypeId, TypeId.TYPED_ENUM, identityKind)}; } `; break; - case TypeId.NAMED_ENUM: + } + case TypeId.NAMED_ENUM: { + const wireNs = this.scope.uniqueName("wireNs"); + const wireName = this.scope.uniqueName("wireName"); bodyStmt = ` if (${wireTypeId} === ${TypeId.NAMED_ENUM}) { ${ @@ -131,8 +138,11 @@ class EnumSerializerGenerator extends BaseSerializerGenerator { this.typeInfo.typeName, )};` : ` - ${this.builder.metaStringResolver.readNamespace()} - ${this.builder.metaStringResolver.readTypeName()} + const ${wireNs} = ${this.builder.metaStringResolver.readNamespace()}; + const ${wireName} = ${this.builder.metaStringResolver.readTypeName()}; + if (${wireNs} !== ${CodecBuilder.sourceString(this.typeInfo.namespace)} || ${wireName} !== ${CodecBuilder.sourceString(this.typeInfo.typeName)}) { + ${this.builder.typeMetaResolver.throwNamedTypeMismatch(TypeId.NAMED_ENUM, this.typeInfo.namespace, this.typeInfo.typeName, wireNs, wireName)}; + } ` } } else { @@ -140,6 +150,7 @@ class EnumSerializerGenerator extends BaseSerializerGenerator { } `; break; + } default: break; } diff --git a/javascript/packages/core/lib/gen/ext.ts b/javascript/packages/core/lib/gen/ext.ts index e7d78df0f4..eccd04898e 100644 --- a/javascript/packages/core/lib/gen/ext.ts +++ b/javascript/packages/core/lib/gen/ext.ts @@ -101,23 +101,33 @@ class ExtSerializerGenerator extends BaseSerializerGenerator { } `; break; - case TypeId.TYPED_EXT: + case TypeId.TYPED_EXT: { + const wireUserTypeId = this.scope.uniqueName("wireUserTypeId"); bodyStmt = ` if (${wireTypeId} === ${TypeId.TYPED_EXT}) { - ${this.builder.reader.readVarUint32Small7()}; + const ${wireUserTypeId} = ${this.builder.reader.readVarUint32Small7()}; + if (${wireUserTypeId} !== ${this.typeInfo.userTypeId}) { + ${this.builder.typeMetaResolver.throwUserTypeIdMismatch(TypeId.TYPED_EXT, this.typeInfo.userTypeId, wireUserTypeId)}; + } } else { ${this.builder.typeMetaResolver.readAsymmetricNonEvolvingTypeInfo(wireTypeId, TypeId.TYPED_EXT, identityKind)}; } `; break; - case TypeId.NAMED_EXT: + } + case TypeId.NAMED_EXT: { + const wireNs = this.scope.uniqueName("wireNs"); + const wireName = this.scope.uniqueName("wireName"); bodyStmt = ` if (${wireTypeId} === ${TypeId.NAMED_EXT}) { ${ !this.builder.resolver.isCompatible() ? ` - ${this.builder.metaStringResolver.readNamespace()}; - ${this.builder.metaStringResolver.readTypeName()}; + const ${wireNs} = ${this.builder.metaStringResolver.readNamespace()}; + const ${wireName} = ${this.builder.metaStringResolver.readTypeName()}; + if (${wireNs} !== ${CodecBuilder.sourceString(this.typeInfo.namespace)} || ${wireName} !== ${CodecBuilder.sourceString(this.typeInfo.typeName)}) { + ${this.builder.typeMetaResolver.throwNamedTypeMismatch(TypeId.NAMED_EXT, this.typeInfo.namespace, this.typeInfo.typeName, wireNs, wireName)}; + } ` : `${this.builder.typeMetaResolver.readNamedTypeMeta( TypeId.NAMED_EXT, @@ -131,6 +141,7 @@ class ExtSerializerGenerator extends BaseSerializerGenerator { } `; break; + } } return ` const ${wireTypeId} = ${this.builder.reader.readUint8()}; diff --git a/javascript/packages/core/lib/gen/struct.ts b/javascript/packages/core/lib/gen/struct.ts index 61de670e99..944eee95f0 100644 --- a/javascript/packages/core/lib/gen/struct.ts +++ b/javascript/packages/core/lib/gen/struct.ts @@ -1203,16 +1203,23 @@ class StructSerializerGenerator extends BaseSerializerGenerator { } `; break; - case TypeId.TYPED_STRUCT: + case TypeId.TYPED_STRUCT: { + const wireUserTypeId = this.scope.uniqueName("wireUserTypeId"); bodyStmt = ` if (${wireTypeId} === ${TypeId.TYPED_STRUCT}) { - ${this.builder.reader.readVarUint32Small7()}; + const ${wireUserTypeId} = ${this.builder.reader.readVarUint32Small7()}; + if (${wireUserTypeId} !== ${this.typeInfo.userTypeId}) { + ${this.builder.typeMetaResolver.throwUserTypeIdMismatch(TypeId.TYPED_STRUCT, this.typeInfo.userTypeId, wireUserTypeId)}; + } } else { ${this.builder.typeMetaResolver.readAsymmetricNonEvolvingTypeInfo(wireTypeId, TypeId.TYPED_STRUCT, identityKind)}; } `; break; - case TypeId.NAMED_STRUCT: + } + case TypeId.NAMED_STRUCT: { + const wireNs = this.scope.uniqueName("wireNs"); + const wireName = this.scope.uniqueName("wireName"); bodyStmt = ` if (${wireTypeId} === ${TypeId.NAMED_STRUCT}) { ${ @@ -1224,8 +1231,11 @@ class StructSerializerGenerator extends BaseSerializerGenerator { "serializer", )};` : ` - ${this.builder.metaStringResolver.readNamespace()}; - ${this.builder.metaStringResolver.readTypeName()}; + const ${wireNs} = ${this.builder.metaStringResolver.readNamespace()}; + const ${wireName} = ${this.builder.metaStringResolver.readTypeName()}; + if (${wireNs} !== ${CodecBuilder.sourceString(this.typeInfo.namespace)} || ${wireName} !== ${CodecBuilder.sourceString(this.typeInfo.typeName)}) { + ${this.builder.typeMetaResolver.throwNamedTypeMismatch(TypeId.NAMED_STRUCT, this.typeInfo.namespace, this.typeInfo.typeName, wireNs, wireName)}; + } ` } } else { @@ -1233,6 +1243,7 @@ class StructSerializerGenerator extends BaseSerializerGenerator { } `; break; + } default: break; } diff --git a/javascript/packages/core/lib/gen/union.ts b/javascript/packages/core/lib/gen/union.ts index d24d8e0d9b..16937c8d58 100644 --- a/javascript/packages/core/lib/gen/union.ts +++ b/javascript/packages/core/lib/gen/union.ts @@ -291,16 +291,23 @@ class UnionSerializerGenerator extends BaseSerializerGenerator { } `; break; - case TypeId.TYPED_UNION: + case TypeId.TYPED_UNION: { + const wireUserTypeId = this.scope.uniqueName("wireUserTypeId"); bodyStmt = ` if (${wireTypeId} === ${TypeId.TYPED_UNION}) { - ${this.builder.reader.readVarUint32Small7()}; + const ${wireUserTypeId} = ${this.builder.reader.readVarUint32Small7()}; + if (${wireUserTypeId} !== ${this.typeInfo.userTypeId}) { + ${this.builder.typeMetaResolver.throwUserTypeIdMismatch(TypeId.TYPED_UNION, this.typeInfo.userTypeId, wireUserTypeId)}; + } } else { ${this.builder.typeMetaResolver.readAsymmetricNonEvolvingTypeInfo(wireTypeId, TypeId.TYPED_UNION, identityKind)}; } `; break; - case TypeId.NAMED_UNION: + } + case TypeId.NAMED_UNION: { + const wireNs = this.scope.uniqueName("wireNs"); + const wireName = this.scope.uniqueName("wireName"); bodyStmt = ` if (${wireTypeId} === ${TypeId.NAMED_UNION}) { ${ @@ -311,8 +318,11 @@ class UnionSerializerGenerator extends BaseSerializerGenerator { this.typeInfo.typeName, )};` : ` - ${this.builder.metaStringResolver.readNamespace()}; - ${this.builder.metaStringResolver.readTypeName()}; + const ${wireNs} = ${this.builder.metaStringResolver.readNamespace()}; + const ${wireName} = ${this.builder.metaStringResolver.readTypeName()}; + if (${wireNs} !== ${CodecBuilder.sourceString(this.typeInfo.namespace)} || ${wireName} !== ${CodecBuilder.sourceString(this.typeInfo.typeName)}) { + ${this.builder.typeMetaResolver.throwNamedTypeMismatch(TypeId.NAMED_UNION, this.typeInfo.namespace, this.typeInfo.typeName, wireNs, wireName)}; + } ` } } else { @@ -320,6 +330,7 @@ class UnionSerializerGenerator extends BaseSerializerGenerator { } `; break; + } } return ` const ${wireTypeId} = ${this.builder.reader.readUint8()}; diff --git a/javascript/test/fory2.test.ts b/javascript/test/fory2.test.ts index fbbf0740f0..c4c8330e23 100644 --- a/javascript/test/fory2.test.ts +++ b/javascript/test/fory2.test.ts @@ -484,4 +484,91 @@ describe("fory 2.0", () => { // Unregistered BY_ID type passed to serialize/deserialize must also fail after freeze. expect(() => f2.serialize({ y: 2 }, B)).toThrow(/must be registered before first use/); }); + + test("rejects conflicting registered identities for enum, ext, union, and non-evolving struct", () => { + for (const compatible of [true, false]) { + const fory = new Fory({ compatible }); + + const EnumA = { RED: "red", GREEN: "green" } as const; + const EnumB = { BLUE: "blue", YELLOW: "yellow" } as const; + const enumASchema = Type.enum(41, EnumA); + const enumBSchema = Type.enum(42, EnumB); + const enumUnboundSchema = Type.enum(EnumB); + const namedEnumASchema = Type.enum("test.EnumA", EnumA); + const namedEnumBSchema = Type.enum("test.EnumB", EnumB); + + class ExtA { + n = 0; + } + class ExtB { + n = 0; + } + Type.ext(51)(ExtA); + Type.ext(52)(ExtB); + const extImpl = { + write(ctx: WriteContext, v: { n: number }) { + ctx.writeInt32(v.n); + }, + read(ctx: ReadContext, result: { n: number }) { + result.n = ctx.readInt32(); + }, + }; + + const unionASchema = Type.union(61, { 0: Type.int32(), 1: Type.string() }); + const unionBSchema = Type.union(62, { 0: Type.int32(), 1: Type.string() }); + + const structASchema = Type.struct(71, { x: Type.int32() }); + const structBSchema = Type.struct(72, { x: Type.int32() }); + + const regEnumA = fory.register(enumASchema); + const regEnumB = fory.register(enumBSchema); + const regUnboundEnum = fory.register(enumUnboundSchema); + const regNamedEnumA = fory.register(namedEnumASchema); + const regNamedEnumB = fory.register(namedEnumBSchema); + const regExtA = fory.register(ExtA, extImpl); + const regExtB = fory.register(ExtB, extImpl); + const regUnionA = fory.register(unionASchema); + const regUnionB = fory.register(unionBSchema); + const regStructA = fory.register(structASchema); + const regStructB = fory.register(structBSchema); + + // Matching IDs succeed. + const enumABytes = regEnumA.serialize(EnumA.RED); + expect(fory.deserialize(enumABytes, enumASchema)).toBe(EnumA.RED); + expect(regEnumA.deserialize(enumABytes)).toBe(EnumA.RED); + // Conflicting known numeric enum ID must fail on both registered and unbound targets. + expect(() => fory.deserialize(enumABytes, enumBSchema)).toThrow(/identity mismatch/i); + expect(() => regEnumB.deserialize(enumABytes)).toThrow(/identity mismatch/i); + expect(() => regUnboundEnum.deserialize(enumABytes)).toThrow(/identity mismatch/i); + + // Matching named enums succeed; conflicting named enums fail. + const namedEnumABytes = regNamedEnumA.serialize(EnumA.RED); + expect(regNamedEnumA.deserialize(namedEnumABytes)).toBe(EnumA.RED); + expect(() => regNamedEnumB.deserialize(namedEnumABytes)).toThrow(/mismatch/i); + expect(() => regUnboundEnum.deserialize(namedEnumABytes)).toThrow(/identity mismatch/i); + + // Asymmetric unknown wire enum ID still adapts to an unbound enum target. + const separateWriter = new Fory({ compatible }); + const unknownEnumBytes = separateWriter.register(Type.enum(999, EnumA)).serialize(EnumA.RED); + expect(regUnboundEnum.deserialize(unknownEnumBytes)).toBe(EnumB.BLUE); + + // EXT conflicts fail; matching succeeds. + const extABytes = regExtA.serialize({ n: 123 }); + expect((regExtA.deserialize(extABytes) as ExtA).n).toBe(123); + expect(() => regExtB.deserialize(extABytes)).toThrow(/identity mismatch/i); + expect(() => fory.deserialize(extABytes, ExtB)).toThrow(/identity mismatch/i); + + // Union conflicts fail; matching succeeds. + const unionABytes = regUnionA.serialize({ case: 0, value: 7 }); + expect(regUnionA.deserialize(unionABytes)).toEqual({ case: 0, value: 7 }); + expect(() => regUnionB.deserialize(unionABytes)).toThrow(/identity mismatch/i); + expect(() => fory.deserialize(unionABytes, unionBSchema)).toThrow(/identity mismatch/i); + + // Struct conflicts fail; matching succeeds. + const structABytes = regStructA.serialize({ x: 9 }); + expect(regStructA.deserialize(structABytes)).toEqual({ x: 9 }); + expect(() => regStructB.deserialize(structABytes)).toThrow(/mismatch/i); + expect(() => fory.deserialize(structABytes, structBSchema)).toThrow(/mismatch/i); + } + }); }); diff --git a/swift/Sources/Fory/FieldSkipper.swift b/swift/Sources/Fory/FieldSkipper.swift index 93a38b8d57..067b3fd694 100644 --- a/swift/Sources/Fory/FieldSkipper.swift +++ b/swift/Sources/Fory/FieldSkipper.swift @@ -491,7 +491,7 @@ extension ReadContext { return [:] } - private func readSkippedUnion() throws -> Any { + internal func readSkippedUnion() throws -> Any { _ = try buffer.readVarUInt32() // The selected TypeInfo owns the materialization depth. Route through // readSkippedValue so unregistered union payloads can also be skipped. diff --git a/swift/Sources/Fory/ReadContext.swift b/swift/Sources/Fory/ReadContext.swift index 6a035d8c86..f9cfe02240 100644 --- a/swift/Sources/Fory/ReadContext.swift +++ b/swift/Sources/Fory/ReadContext.swift @@ -267,6 +267,9 @@ public final class ReadContext { if wireTypeID == .namedEnum { return TypeInfo.skippedEnum() } + if wireTypeID == .namedUnion { + return TypeInfo.skippedUnion() + } throw ForyError.typeNotRegistered("namespace=\(namespace.value), type=\(typeName.value)") case .typedEnum, .typedStruct, .typedExt, .typedUnion: let userTypeID = try buffer.readVarUInt32() @@ -276,10 +279,15 @@ public final class ReadContext { if wireTypeID == .typedEnum { return TypeInfo.skippedEnum() } + if wireTypeID == .typedUnion { + return TypeInfo.skippedUnion() + } throw ForyError.typeNotRegistered("user_type_id=\(userTypeID)") case .enumType: return TypeInfo.skippedEnum() - case .structType, .ext, .union: + case .union: + return TypeInfo.skippedUnion() + case .structType, .ext: throw ForyError.typeNotRegistered( "cannot skip UNBOUND non-evolving type \(wireTypeID) without field metadata" ) @@ -608,6 +616,9 @@ extension ReadContext { if wireTypeID == .namedEnum { return TypeInfo.skippedEnum() } + if wireTypeID == .namedUnion { + return TypeInfo.skippedUnion() + } throw missingDynamicCompatibleOwner(entry.wireTypeMeta) } diff --git a/swift/Sources/Fory/TypeResolver.swift b/swift/Sources/Fory/TypeResolver.swift index c137c66b3e..5d42ab6aa9 100644 --- a/swift/Sources/Fory/TypeResolver.swift +++ b/swift/Sources/Fory/TypeResolver.swift @@ -601,6 +601,30 @@ public final class TypeInfo: @unchecked Sendable { ) } + static func skippedUnion() -> TypeInfo { + let readUnion: (ReadContext) throws -> Any = { context in + try context.readSkippedUnion() + } + return TypeInfo( + serializerTypeID: ObjectIdentifier(TypeInfo.self), + targetTypeID: ObjectIdentifier(TypeInfo.self), + typeID: .union, + userTypeID: nil, + identityKind: .unbound, + evolving: false, + namespace: MetaString.empty(specialChar1: ".", specialChar2: "_"), + typeName: MetaString.empty(specialChar1: "$", specialChar2: "_"), + typeDefHasUserTypeFields: false, + isRefType: false, + readDataAlwaysAdvances: true, + writer: { _, _ in + throw ForyError.invalidData("skipped unknown union cannot be written") + }, + reader: readUnion, + compatibleReader: { context, _ in try readUnion(context) } + ) + } + @inline(__always) func matches( typeID: TypeId, diff --git a/swift/Tests/ForyTests/Fory20Tests.swift b/swift/Tests/ForyTests/Fory20Tests.swift index 882741e58e..d04a8d9d43 100644 --- a/swift/Tests/ForyTests/Fory20Tests.swift +++ b/swift/Tests/ForyTests/Fory20Tests.swift @@ -109,6 +109,29 @@ private enum Fory20UnregisteredUnion: Equatable { case unknown(UnknownCase) } +@ForyUnion +private enum Fory20NestedOuterUnion: Equatable { + case number(Int32) + case nested(Fory20UnregisteredUnion) + @ForyUnknownCase + case unknown(UnknownCase) +} + +@ForyStruct +private struct Fory20SkipNestedUnionV1: Equatable { + @ForyField(id: 1) + var removed: Fory20NestedOuterUnion = .number(0) + + @ForyField(id: 2) + var kept: String = "" +} + +@ForyStruct +private struct Fory20SkipNestedUnionV2: Equatable { + @ForyField(id: 2) + var kept: String = "" +} + @ForyStruct private final class Fory20CycleNode { var name: String = "" @@ -407,3 +430,52 @@ func fory20RegistrationFreezeAfterSuccessAndFailure() throws { try afterFailure.register(Fory20Vector2D.self, id: 502) } } + +@Test +func fory20CompatibleSkipNestedUnions() throws { + // 1. Unregistered outer union holding an unregistered inner union containing an Int32. + let unboundWriter = Fory(config: .init(trackRef: true, compatible: true)) + let reader = Fory(config: .init(trackRef: true, compatible: true)) + let unboundInput = Fory20SkipNestedUnionV1( + removed: .nested(.number(42)), + kept: "after-unbound-nested-union" + ) + let unboundDecoded: Fory20SkipNestedUnionV2 = try reader.deserialize( + try unboundWriter.serialize(unboundInput) + ) + #expect(unboundDecoded.kept == "after-unbound-nested-union") + + // 2. Unregistered outer union holding an inner union with an unregistered struct payload. + let structPayloadInput = Fory20SkipNestedUnionV1( + removed: .nested(.payload(Fory20UnionPayload(tag: "nested", score: 77))), + kept: "after-nested-union-struct" + ) + let structPayloadDecoded: Fory20SkipNestedUnionV2 = try reader.deserialize( + try unboundWriter.serialize(structPayloadInput) + ) + #expect(structPayloadDecoded.kept == "after-nested-union-struct") + + // 3. TYPED_UNION inner union registered only on the writer. + let typedWriter = Fory(config: .init(trackRef: true, compatible: true)) + try typedWriter.register(Fory20UnregisteredUnion.self, id: 9101) + let typedInput = Fory20SkipNestedUnionV1( + removed: .nested(.number(123)), + kept: "after-typed-nested-union" + ) + let typedDecoded: Fory20SkipNestedUnionV2 = try reader.deserialize( + try typedWriter.serialize(typedInput) + ) + #expect(typedDecoded.kept == "after-typed-nested-union") + + // 4. NAMED_UNION inner union registered only on the writer. + let namedWriter = Fory(config: .init(trackRef: true, compatible: true)) + try namedWriter.register(Fory20UnregisteredUnion.self, name: "test.NestedInnerUnion") + let namedInput = Fory20SkipNestedUnionV1( + removed: .nested(.number(456)), + kept: "after-named-nested-union" + ) + let namedDecoded: Fory20SkipNestedUnionV2 = try reader.deserialize( + try namedWriter.serialize(namedInput) + ) + #expect(namedDecoded.kept == "after-named-nested-union") +} From fdbe22dd66fc80d11766af5c5b8d57d50222f927 Mon Sep 17 00:00:00 2001 From: chaokunyang Date: Fri, 4 Dec 2026 14:38:09 +0800 Subject: [PATCH 2/2] fix(go,java): mark Go xlang test enums and satisfy Java checkstyle --- go/fory/tests/xlang/xlang_test_main.go | 4 ++++ .../java/org/apache/fory/meta/TypeDef.java | 21 ++++++++++--------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/go/fory/tests/xlang/xlang_test_main.go b/go/fory/tests/xlang/xlang_test_main.go index a98b9a72ae..f895abd0ad 100644 --- a/go/fory/tests/xlang/xlang_test_main.go +++ b/go/fory/tests/xlang/xlang_test_main.go @@ -232,6 +232,8 @@ func assertEqualFloat64(expected, actual float64, name string) { type Color int32 +func (Color) ForyEnumMarker() {} + const ( GREEN Color = 0 RED Color = 1 @@ -264,6 +266,8 @@ type TwoStringFieldStruct struct { // Enum field structs for testing type TestEnum int32 +func (TestEnum) ForyEnumMarker() {} + const ( VALUE_A TestEnum = 0 VALUE_B TestEnum = 1 diff --git a/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java b/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java index d0f4b26447..e2c750ef39 100644 --- a/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java +++ b/java/fory-core/src/main/java/org/apache/fory/meta/TypeDef.java @@ -610,19 +610,20 @@ private List buildDescriptors( anchors.add(new int[] {remoteCount, localCount}); unboundLayerAlignments = new HashMap<>(); for (int a = 0; a < anchors.size() - 1; a++) { - int rStart = anchors.get(a)[0] + 1; - int rEnd = anchors.get(a + 1)[0]; - int lStart = anchors.get(a)[1] + 1; - int lEnd = anchors.get(a + 1)[1]; - int rLen = rEnd - rStart; - int lLen = lEnd - lStart; - boolean exact = rLen == lLen; - for (int r = rStart; r < rEnd; r++) { + int remoteStart = anchors.get(a)[0] + 1; + int remoteEnd = anchors.get(a + 1)[0]; + int localStart = anchors.get(a)[1] + 1; + int localEnd = anchors.get(a + 1)[1]; + int remoteLen = remoteEnd - remoteStart; + int localLen = localEnd - localStart; + boolean exact = remoteLen == localLen; + for (int r = remoteStart; r < remoteEnd; r++) { String remoteLayer = remoteLayers.get(r); if (remoteLayer.startsWith(UNBOUND_LAYER_PREFIX)) { - int localIdx = exact ? (lStart + (r - rStart)) : (lEnd - (rEnd - r)); + int localIdx = + exact ? (localStart + (r - remoteStart)) : (localEnd - (remoteEnd - r)); unboundLayerAlignments.put( - remoteLayer, new UnboundLayerAlignment(localIdx, lStart, lEnd, exact)); + remoteLayer, new UnboundLayerAlignment(localIdx, localStart, localEnd, exact)); } } }