Skip to content

fix(kafka): remove Native AOT warnings from Kafka serializers - #1373

Merged
hjgraca merged 1 commit into
developfrom
fix/kafka-aot-warnings
Nov 25, 2026
Merged

hjgraca merged 1 commit into
developfrom
fix/kafka-aot-warnings

Conversation

@hjgraca

@hjgraca hjgraca commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

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:

MissingMethodException: No parameterless constructor defined for type
'AWS.Lambda.Powertools.Kafka.Avro.ConsumerRecords`2[AvroKey,AvroProduct]'
  at PowertoolsKafkaSerializerBase.CreateConsumerRecordsInstance(Type)

Deserialize<T> is the ILambdaSerializer entry 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:

 Deserialize<T>(stream)                              // T = ConsumerRecords<TKey, TValue>
-  MakeGenericType(Dictionary/List/ConsumerRecord<TKey, TValue>)
-  Activator.CreateInstance(...) + PropertyInfo.SetValue(...)   // per record
+  Activator.CreateInstance<T>()                      // one justified IL2091 suppression, see below
+  ((IPopulatableConsumerRecords)records).Populate(root, this)
+    ConsumerRecords<[DAM] TKey, [DAM] TValue>         // key and value types known statically here
+      PopulateConsumerRecords<TKey, TValue>          // new ConsumerRecord<TKey, TValue>, typed setters
+        DeserializeKey(bytes, typeof(TKey))          // DAM flows from the user's handler signature
+        DeserializeValue(base64, typeof(TValue))

How each warning group from the issue was handled:

Warning group Decision
MakeGenericType, Activator.CreateInstance(Type), GetProperty/SetValue on ConsumerRecords/ConsumerRecord/Dictionary/List (IL2067, IL2070, IL3050, SetProperty IL2026) Real fix. Records are built with typed code inside ConsumerRecords<TK, T> through an internal interface. No reflection.
Reflection over user key/value types: Avro _SCHEMA, Protobuf Parser, constructors (IL2067 on DeserializeKey/ProcessValue, IL2070 GetProtobufParser) Real fix. [DynamicallyAccessedMembers(PublicParameterlessConstructor | PublicProperties | PublicFields)] on the TK and T type parameters of ConsumerRecords<TK, T>, so the trimmer keeps those members of the types in the user's handler signature. GetProtobufParser gets PublicProperties.
[RequiresUnreferencedCode]/[RequiresDynamicCode] on DeserializeValue, DeserializeFormatSpecific, DeserializeComplexTypeFormat and the Avro/Protobuf/Json overrides Removed, because the code behind them no longer needs them. Their Type parameters keep their DynamicallyAccessedMembers.
Reflection-based System.Text.Json in Deserialize<T>, Serialize<T> and the JSON format (#pragma, which ILC ignores) Guarded. Moved to small [RequiresUnreferencedCode] helpers that are only called under JsonSerializer.IsReflectionEnabledByDefault && RuntimeFeatureWrapper.IsDynamicCodeSupported. Without reflection: the JsonSerializerContext, then the options' TypeInfoResolver, then (for Serialize) a built-in context for string/bool/int/long/double/decimal, otherwise an InvalidOperationException that names the type to add.
GetJsonTypeInfo<T>() scanning the context's properties (IL2075) Real fix. Replaced with SerializerContext.GetTypeInfo(typeof(T)).
Activator.CreateInstance for defaults of primitive values and empty JSON structs (IL2067) Real fix. Primitives use a TypeCode switch. Empty JSON structs use the context's CreateObject, reflection when enabled, and otherwise null, which the typed setter turns into default.
IL2092 on the Avro override Fixed. Its annotation now matches the base method.
Activator.CreateInstance<T>() with an unannotated T (IL2091) Justified suppression, the only one. T is checked to be ConsumerRecords<,> first, and [DynamicDependency] keeps that constructor for ILLink. ILC compiles CreateInstance<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 unannotated T to TKey/TValue without an instance.
Avro.Specific.ObjectCreator (8 warnings, upstream) Documented. Records with only primitive and enum fields work as they are. Nested records, arrays and maps need TrimmerRootAssembly plus [DynamicDependency] on List<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 in docs/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:

orders/0/15 ... key=(1,Green) product=(1001,Laptop,999,99) header=corr-0 valueSchema=BINARY/
orders/0/16 ... key=(2,Red) product=(1002,Smartphone,499,5) header=corr-1 valueSchema=BINARY/7   # Confluent framing
RESPONSE: "Processed 2 records"

JSON without a context under AOT now fails with guidance, where before it failed with a MissingMethodException:

Failed to deserialize key data: Can't deserialize 'OrderKey' because reflection-based JSON serialization is disabled,
for example in Native AOT and trimmed apps. Pass a JsonSerializerContext that includes
[JsonSerializable(typeof(OrderKey))] to the PowertoolsKafkaJsonSerializer constructor.

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] on TK and T, plus an internal interface. Code that is generic over ConsumerRecords<TK, T> with its own unannotated type parameters gets IL2091 if it enables trim analysis.
  • Protected DeserializeValue, DeserializeFormatSpecific and DeserializeComplexTypeFormat no longer carry [RequiresUnreferencedCode]/[RequiresDynamicCode]. A third-party subclass whose override keeps them gets IL2046 when it enables trim analysis.
  • Serialize<T> without reflection: string and common primitives work without a context, and other types throw InvalidOperationException instead 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 a JsonSerializerContext happens to include ConsumerRecords<,>. 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, TrimmerRootAssembly of the package, packed from this branch), Powertools-owned warnings:

Package develop This PR Remaining (total)
Kafka.Json 26 0 0
Kafka.Avro 27 0 8, all Avro.Specific.ObjectCreator, identical to develop
Kafka.Protobuf 27 0 0

Each package's Release library build also reports 0 IL warnings from the Kafka sources.

Native AOT runtime. Top-level LambdaBootstrapBuilder apps against a fake Runtime API on 127.0.0.1, each run as JIT and as Native AOT:

App 3.2.2 AOT This PR AOT Matches JIT
Json: ConsumerRecords<OrderKey, Product> with a JsonSerializerContext MissingMethodException (ConsumerRecords ctor) works yes
Avro: ConsumerRecords<AvroKey, AvroProduct> (enum in the key), no extra config MissingMethodException works yes
Avro: Order with nested record, array and map, TrimmerRootAssembly + [DynamicDependency] n/a works yes
Avro: same Order, no extra config n/a MissingMethodException for Address, then List<OrderLine> (upstream, now documented) n/a
Protobuf: ConsumerRecords<ProtobufKey, ProtobufProduct>, plain + Confluent-framed values MissingMethodException works yes
Protobuf, PublishTrimmed (ILLink, JIT) n/a works, 0 Powertools warnings yes

Unit tests: AWS.Lambda.Powertools.Kafka.Tests, 117 passed on net8.0 and net10.0, in Debug and Release. New NativeAotCompatibilityTests switch off reflection through every copy of RuntimeFeatureWrapper (Release embeds one per package) and run in a non-parallel collection:

Json, no context, reflection off          -> SerializationException(InvalidOperationException naming the type)   red before, green after
Deserialize<TestModel>, no context, off   -> InvalidOperationException naming the type                            red before, green after
Serialize<TestModel>, no context, off     -> InvalidOperationException naming the type                            red before, green after
Serialize("..."), no context, off         -> "\"Processed 3 records\"" (no BOM)                                   red before, green after
Serialize via options TypeInfoResolver    -> exact JSON (no BOM)                                                   red before, green after
Json with context / options resolver, Avro, Protobuf, primitives, empty struct values, reflection off -> deserialize

Pinned before the change and green on develop: unparseable primitive defaults (byte, float, decimal, DateTime, IntPtr, ...), an empty JSON value for a struct becoming default, and an event without records.

The full CI build (dotnet restore && dotnet build --configuration Release --no-restore from libraries/) 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:

  • Migration process documented
  • Implement warnings (if it can live side by side)

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.

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
@hjgraca hjgraca added bug Unexpected, reproducible and unintended software behaviour aot area/kafka labels Nov 25, 2026
@boring-cyborg boring-cyborg Bot added documentation Improvements or additions to documentation tests labels Nov 25, 2026
@powertools-for-aws-oss-automation powertools-for-aws-oss-automation Bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Nov 25, 2026
@sonarqubecloud

Copy link
Copy Markdown

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.80556% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.49%. Comparing base (57c40dc) to head (d8c6ced).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
....Powertools.Kafka/PowertoolsKafkaSerializerBase.cs 85.18% 6 Missing and 10 partials ⚠️
...rtools.Kafka.Json/PowertoolsKafkaJsonSerializer.cs 90.90% 0 Missing and 3 partials ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@hjgraca
hjgraca merged commit 0397cd5 into develop Nov 25, 2026
12 checks passed
@hjgraca
hjgraca deleted the fix/kafka-aot-warnings branch November 25, 2026 18:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

aot area/kafka bug Unexpected, reproducible and unintended software behaviour documentation Improvements or additions to documentation size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Native AOT warnings in Kafka (Json, Avro, Protobuf)

1 participant