Repository navigation
fix(kafka): remove Native AOT warnings from Kafka serializers - #1373
Merged
Merged
Conversation
ConsumerRecords<TK, T> is now built without reflection: the instance populates itself through an internal interface, where the key and value types are known statically. The key and value type parameters carry DynamicallyAccessedMembers so trimming keeps the Avro _SCHEMA field, the Protobuf Parser property and the parameterless constructor. Reflection-based System.Text.Json is only used behind the JsonSerializer.IsReflectionEnabledByDefault feature switch. Without it, the JsonSerializerContext, then the TypeInfoResolver of the options are used, and string and common primitive return values serialize without a context. Unsupported types throw an InvalidOperationException that names the type. Also fixes the IL2092 annotation mismatch on the Avro override. Refs #1333
|
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #1373 +/- ##
===========================================
+ Coverage 80.29% 80.49% +0.20%
===========================================
Files 303 303
Lines 12962 12972 +10
Branches 1551 1548 -3
===========================================
+ Hits 10408 10442 +34
+ Misses 2098 2082 -16
+ Partials 456 448 -8 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Issue number: closes #1333
Summary
Changes
On 3.2.2, every Kafka package fails at the first step in a Native AOT binary, for all three formats, and the build gives no warning from the user's code:
Deserialize<T>is theILambdaSerializerentry point, so[RequiresUnreferencedCode]can't be put on it (it would have to match the interface). The fix makes the documented path AOT-safe instead of annotating it:How each warning group from the issue was handled:
MakeGenericType,Activator.CreateInstance(Type),GetProperty/SetValueonConsumerRecords/ConsumerRecord/Dictionary/List(IL2067, IL2070, IL3050,SetPropertyIL2026)ConsumerRecords<TK, T>through an internal interface. No reflection._SCHEMA, ProtobufParser, constructors (IL2067 onDeserializeKey/ProcessValue, IL2070GetProtobufParser)[DynamicallyAccessedMembers(PublicParameterlessConstructor | PublicProperties | PublicFields)]on theTKandTtype parameters ofConsumerRecords<TK, T>, so the trimmer keeps those members of the types in the user's handler signature.GetProtobufParsergetsPublicProperties.[RequiresUnreferencedCode]/[RequiresDynamicCode]onDeserializeValue,DeserializeFormatSpecific,DeserializeComplexTypeFormatand the Avro/Protobuf/Json overridesTypeparameters keep theirDynamicallyAccessedMembers.System.Text.JsoninDeserialize<T>,Serialize<T>and the JSON format (#pragma, which ILC ignores)[RequiresUnreferencedCode]helpers that are only called underJsonSerializer.IsReflectionEnabledByDefault && RuntimeFeatureWrapper.IsDynamicCodeSupported. Without reflection: theJsonSerializerContext, then the options'TypeInfoResolver, then (forSerialize) a built-in context forstring/bool/int/long/double/decimal, otherwise anInvalidOperationExceptionthat names the type to add.GetJsonTypeInfo<T>()scanning the context's properties (IL2075)SerializerContext.GetTypeInfo(typeof(T)).Activator.CreateInstancefor defaults of primitive values and empty JSON structs (IL2067)TypeCodeswitch. Empty JSON structs use the context'sCreateObject, reflection when enabled, and otherwisenull, which the typed setter turns intodefault.Activator.CreateInstance<T>()with an unannotatedT(IL2091)Tis checked to beConsumerRecords<,>first, and[DynamicDependency]keeps that constructor for ILLink. ILC compilesCreateInstance<T>()to a generic-dictionary lookup of the instantiation's constructor, so no reflection metadata is needed. Verified with a Native AOT binary and a trimmed (ILLink, JIT) binary. No other trick goes from an unannotatedTtoTKey/TValuewithout an instance.Avro.Specific.ObjectCreator(8 warnings, upstream)TrimmerRootAssemblyplus[DynamicDependency]onList<T>/Dictionary<string, T>. Both were verified at runtime.Docs: new Native AOT section in
docs/utilities/kafka.md(per-format table, a JSON example with a context, an Avro example with collections, the Apache.Avro warning), with compiled snippets indocs/snippets/kafka/NativeAot.cs.User experience
A Native AOT function written as the docs show now runs. Here is the same binary against a local Runtime API, with complex keys, headers and schema metadata:
JSON without a context under AOT now fails with guidance, where before it failed with a
MissingMethodException:JIT behaviour doesn't change: reflection is enabled there, so the same paths as before run.
Public API: no signatures added, removed or renamed.
ConsumerRecords<TK, T>:[DynamicallyAccessedMembers]onTKandT, plus an internal interface. Code that is generic overConsumerRecords<TK, T>with its own unannotated type parameters gets IL2091 if it enables trim analysis.DeserializeValue,DeserializeFormatSpecificandDeserializeComplexTypeFormatno longer carry[RequiresUnreferencedCode]/[RequiresDynamicCode]. A third-party subclass whose override keeps them gets IL2046 when it enables trim analysis.Serialize<T>without reflection:stringand common primitives work without a context, and other types throwInvalidOperationExceptioninstead of STJ's error. With reflection enabled it's unchanged, including the existing UTF-8 BOM on that path, which I left alone.Deserialize<ConsumerRecords<,>>always takes the Kafka path, even when aJsonSerializerContexthappens to includeConsumerRecords<,>. The old check meant to do this (typeof(T) != typeof(ConsumerRecords<,>)) compared against the open generic, so it was always true.Evidence
Native AOT harness (.NET 10,
PublishAot,TrimmerRootAssemblyof the package, packed from this branch), Powertools-owned warnings:Avro.Specific.ObjectCreator, identical to developEach package's Release library build also reports 0 IL warnings from the Kafka sources.
Native AOT runtime. Top-level
LambdaBootstrapBuilderapps against a fake Runtime API on 127.0.0.1, each run as JIT and as Native AOT:ConsumerRecords<OrderKey, Product>with aJsonSerializerContextMissingMethodException(ConsumerRecords ctor)ConsumerRecords<AvroKey, AvroProduct>(enum in the key), no extra configMissingMethodExceptionOrderwith nested record, array and map,TrimmerRootAssembly+[DynamicDependency]Order, no extra configMissingMethodExceptionforAddress, thenList<OrderLine>(upstream, now documented)ConsumerRecords<ProtobufKey, ProtobufProduct>, plain + Confluent-framed valuesMissingMethodExceptionPublishTrimmed(ILLink, JIT)Unit tests:
AWS.Lambda.Powertools.Kafka.Tests, 117 passed on net8.0 and net10.0, in Debug and Release. NewNativeAotCompatibilityTestsswitch off reflection through every copy ofRuntimeFeatureWrapper(Release embeds one per package) and run in a non-parallel collection:Pinned before the change and green on develop: unparseable primitive defaults (
byte,float,decimal,DateTime,IntPtr, ...), an empty JSON value for a struct becomingdefault, and an event withoutrecords.The full CI build (
dotnet restore && dotnet build --configuration Release --no-restorefromlibraries/) succeeds, and the docs snippets project builds.Merge Danger
Door: two-way
No signatures change. The annotations and the suppression can be reverted in a later release.
Blast Radius: narrow
All Kafka deserialization now goes through the new typed population code, under JIT too. The existing Avro, Protobuf, JSON, primitive, header and schema-metadata tests cover it, and the JIT runs above match. Users who enable trim analysis may see the new IL2091/IL2046 cases listed under Public API.
Checklist
Please leave checklist items unchecked if they do not apply to your change.
Is this a breaking change?
RFC issue number:
Checklist:
Acknowledgment
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.